
/**itfreer.arcgis.book.js**/
/* 
 * 定义itfreer.arcgis.book模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义itfreer.arcgis.book模块
	 */
	var itfreerArcgisBook = angular.module('itfreer.arcgis.book', 
		['itfreer.form.core',
		'itfreer.arcgis.core']);

	/**
	 * 定义核心模块依赖注入器，定义地图的基础用法
	 */
	itfreerArcgisBook.factory('$itfreer_arcgis_book',
		function($rootScope, $gisObject, $formObject, $itfreer_core, 
			$itfreer_arcgis_core, $itfreer_form_core) {
			$itfreer_arcgis_book = {

				/**
				 * 加载数据
				 */
				initBookData : function(formName, tableName, keyField, randomFields, orderObject, formValue, queryValue, bpmKey, pageSize){
					$itfreer_form_core.initAndLoadData(formName, tableName, keyField, randomFields, orderObject, formValue, queryValue, bpmKey, pageSize);
				},

				/**
				 * 保存数据
				 */
				saveBook : function(formName){
					var row = $formObject[formName].editRow;
					var extent = $gisObject.map.extent;
					row["S_BOOKEXTENT"] = extent.xmin + "," + extent.ymin + "," 
						+ extent.xmax + "," + extent.ymax;

					var date = new Date();
					var y = date.getFullYear();
					var m = date.getMonth() + 1;
					var d = date.getDate();

					row["D_ADDTIME"] = y + '-' + m + '-' + d;
					row["USERID"] = $formObject.user.userid;
					$itfreer_form_core.save(formName);
				},

				/**
				 * 删除数据
				 */
				delBook : function(formName, row){
					$itfreer_form_core.delEntity(formName, row);
				},

				/**
				 * 绽放到
				 */
				extentTo : function(row){
					var extentString = row["S_BOOKEXTENT"];
					var wkid = 0;
					if($gisObject.mapisdlwkid){
						wkid = $gisObject.dlwkid;
					}else{
						wkid = $gisObject.tywkid;
					}
					var extent = $itfreer_arcgis_core.getExtentByString(extentString, wkid);
					$gisObject.map.setExtent(extent);
				}
			};
			for(f in $itfreer_arcgis_book){
				$rootScope[f] = $itfreer_arcgis_book[f];
			}
			return $itfreer_arcgis_book;
		}
	);

	/* 
	 * 加载服务器
	 */
	itfreerArcgisBook.run(function($rootScope, $itfreer_arcgis_book) {
	  	
	});
}(window, angular));
/**itfreer.arcgis.core.js**/
/* itfreer v1.1
 * wdp web应用开发平台
 * 此类定义ArcGIS的基础逻辑，包括绘制器，查询器，定位器，转换器等。
 */
;
/**
 * 初始化ArcGIS变量
 */
(function() {
	
	this.arcGISObject = {};
	this.hasInitFinsh = false;
	this.initFinshEvent = null;

	require(["esri/map",

		"esri/layers/WMSLayer",
		"esri/layers/WMTSLayer", 

        "esri/tasks/geometry",
        "esri/tasks/query",
		"esri/tasks/QueryTask",

		 "esri/graphic",
		 "esri/urlUtils",
		 "esri/units",
			
		"esri/config",
		"esri/geometry/Point",
		"esri/geometry/Circle",
		"esri/geometry/Extent",
		"esri/SpatialReference",
		
		"esri/toolbars/navigation",
		"esri/toolbars/draw",

		"esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
         "esri/dijit/Scalebar",
		"dojo/parser",
		"dojo/domReady!"],
	function (Map,
	          bMapVeclayer, bMapImglayer, bMapAnolayer,
	          tdMapAnnoLayer, tdMapLayer, tdMapImgAnnoLayer, tdMapImgLayer){

		this.hasInitFinsh = true;

	    // arcgis的proxy地址
		esriConfig.defaults.io.proxyUrl = getBasePath() + "/gis/proxy.do";

		if(this.initFinshEvent){
			this.initFinshEvent();
		}
	});
}).call(this);

/* 
 * 定义itfreer.arcgis.core核心模块，提供一些基础地理算法
 */
(function(window, angular, undefined){
	/* 
	 * 定义ArcGIS的核心模块，提供一些基础地理算法
	 */
	var itfreerarcgiscoreModule = angular.module('itfreer.arcgis.core', ['itfreer.core']);

	/* 
	 * 定义gis变量
	 */
	itfreerarcgiscoreModule.value('$gisObject', {
		// 地理坐标系统
		dlwkid : 4326,
		// 投影坐标系统
		tywkid : 102100,
		// 当前的地图是否为地理坐标系统
		mapisdlwkid : true,
		// 主地图
		map : null,
		// 基础地址图层集
		BaseTiledLayer : {},
		// 基础影像图层集
		BaseImageLayer : {},
		// 专题图层集
		Services : {},
		// 导航工具条
		navToolbar : null,
		// 绘制工具条
		drawToolbars : null,
		// 定位器
		locator : null,
		// 当前的定位级别
		locatorLevel : null,
		// 当前的定位地址名称
		locatorAddress : "",
		// geometry服务
		geometryService : null,
		// printing服务
		printingService : null,
		/* 
		 * 定义ArcGIS的各种样式
		 */
		styleConfig : {
			/* 
			 * 绘制样式
			 */
			drawStyle : {
				fillColor : createColorFromHex("#ff0000"),
				fillOpacity : 0.8,
				strokeColor : createColorFromHex("#ff0000"),
				strokeWidth : 2
			},
			/* 
			 * 高亮默认样式
			 */
			highLightDefaultStyle : {
				fillColor : createColorFromHex("#FBDF55"),
				fillOpacity : 0.5,
				strokeColor : createColorFromHex("#666666"),
				strokeWidth : 4
			},
			/* 
			 * 高亮选择样式
			 */
			highLightSelectStyle : {
				fillColor : createColorFromHex("#FA8650"),
				fillOpacity : 0.8,
				strokeColor : createColorFromHex("#3399ff"),
				strokeWidth : 4
			}
		},
		/* 
		 * 查询参数
		 */
		searchParameter : { },
		/* 
		 * 坐标定位参数
		 */
		locatorParameter : {
			// 经纬度 - 经度 - 度
			jdd : '',
			// 经纬度 - 经度 - 分
			jdf : '',
			// 经纬度 - 经度 - 秒
			jdm : '',
			// 经纬度 - 维度 - 度
			wdd : '',
			// 经纬度 - 维度 - 分
			wdf : '',
			// 经纬度 - 维度 - 秒
			wdm : '',
			// 平面坐标 - X
			pmx : '',
			// 平面坐标 - Y
			pmy : '',
			// 地理坐标 - X
			dlx : '',
			// 地理坐标 - Y
			dly : ''
		},
		/**
		 * 是否正在绘制
		 */
		isDrawing:false
	});

	/* 
	 * 定义ArcGIS的绘制模块
	 */
	itfreerarcgiscoreModule.factory('$itfreer_arcgis_core', function($rootScope, $itfreer_core, $gisObject) {
		$itfreer_arcgis_core = {
			/**
			 * 获取要素集的最大视图范围
			 * 
			 * @param { [
			 *            <esri.layer.GraphicLayer>]} features 目标对象
			 * @param {
			 *            <Number>} zoomFactor
			 * @return {esri.geometry.Extent}
			 */
			getMaxExtent : function(features, zoomFactor) {
				if (features.length < 0) {
					return false;
				}
				if (!zoomFactor)
					zoomFactor = 1;
				var extent = new esri.geometry.Extent();  
				//根据第一个不为null的geometry判断geometry类型
				for(var i = 0;i<features.length;i++){
					var _geometry = features[i].geometry;
					if(!_geometry || _geometry == null)
						continue;
					if (_geometry.type == "polygon")
					{
						//将范围进行叠加
						for (var j = 0; j < features.length; j++) {
							if(features[j].geometry)
								if(extent.xmin&&extent.xmax&&extent.ymin&&extent.ymax){
									extent = extent.union(features[j].geometry.getExtent());
								}
								else{
									extent = features[j].geometry.getExtent();
								}
						}
						extent = extent.expand(zoomFactor);
					} else if (_geometry.type == "point") {
						var pointX;
						var pointY;
						var pointXArr = [];
						var pointYArr = [];
						for (var j = 0; j < features.length; j++) {
							if(features[j].geometry){
								pointX = features[j].geometry.x;
								pointY = features[j].geometry.y;
								pointXArr.push(pointX);
								pointYArr.push(pointY);
							}
						}
						var maxX = Math.max.apply(null, pointXArr) + 0.1;
						var minX = Math.min.apply(null, pointXArr) - 0.1;
						var maxY = Math.max.apply(null, pointYArr) + 0.1;
						var minY = Math.min.apply(null, pointYArr) - 0.1;
						extent = new esri.geometry.Extent(minX, minY, maxX, maxY,
								_geometry.spatialReference).expand(zoomFactor);
					} else {
						//将范围进行叠加
						for (var j = 0; j < features.length; j++) {
							if(features[j].geometry)
								if(extent.xmin&&extent.xmax&&extent.ymin&&extent.ymax){
									extent = extent.union(features[j].geometry.getExtent());
								}
								else{
									extent = features[j].geometry.getExtent();
								}
						}
						extent = extent.expand(zoomFactor);
					}
					break;
				}
				// 调整返回的extent大小
				var _x = extent.xmax - extent.xmin;
				var _y = extent.ymax - extent.ymin;
				extent.xmax = extent.xmax + (_x / 3);
				extent.xmin = extent.xmin - (_x / 3);
				extent.ymax = extent.ymax + (_y / 3);
				extent.ymin = extent.ymin - (_y / 3);
				extent.spatialReference = $gisObject.map.spatialReference;
				return extent;
			}, 

			/**
			 * 获取Geometry的中心点
			 * 
			 * @function {public} ?
			 * @param {esri.geometry.Geometry}
			 *            geometry - 几何对象
			 * @return point - 点对象
			 */
			getCenter : function(geometry) {
				var _point;
				if (geometry.type == "point") {
					_point = geometry;
				} else if (geometry.type == "polygon") {
					_point = geometry.getExtent().getCenter();
				} else if(geometry.type == "polyline"){
					var ptnArr = geometry.paths[0][geometry.paths[0].length - 1];
					_point = new esri.geometry.Point(ptnArr[0], ptnArr[1], geometry.spatialReference);
				} else {
					_point = geometry.getExtent().getCenter();
				}
				return _point;
			},

			/**
			 * 根据字符串获取Extent对象
			 * 
			 * @function {public} ?
			 */
			getExtentByString : function(extentStr, wkid) {
				var extentArray = extentStr.split(",");
				var extent = new esri.geometry.Extent({
							"xmin" : parseFloat(extentArray[0]),
							"ymin" : parseFloat(extentArray[1]),
							"xmax" : parseFloat(extentArray[2]),
							"ymax" : parseFloat(extentArray[3]),
							"spatialReference" : wkid
						});
				return extent;
			},

			/**
			 * 重新刷新地图
			 * 
			 * @function {public} ?
			 */
			reflashMap : function() {
				if($gisObject.map){
					$gisObject.map.resize(true);
					$gisObject.map.reposition();
				}
			},

			/**
			 * 获取Graphic
			 */
			getGraphic : function(objectid) {
				var graphic = null;
			   	//遍历地图的graphics查找OBJECTID和点击行的OBJECTID相同的Grapphic
			   	for(var i=0;i<$gisObject.map.graphics.graphics.length;i++){
			      	var cGrapphic=$gisObject.map.graphics.graphics[i];
			      	if(cGrapphic.attributes
			      		&& cGrapphic.attributes.OBJECTID==objectid){
			         	graphic=cGrapphic;
			         	break;
			      	}
			   	}
			   	return graphic;
			},

			/**
			 * 获取小气泡Graphic
			 */
			getGraphicByPop : function(objectid, searchName) {
				var graphic = null;
				var keyName = $gisObject.searchParameter[searchName].keyName;
				if(keyName == null || keyName == ""){
					keyName = "OBJECTID";
				}
			   	//遍历地图的graphics查找OBJECTID和点击行的OBJECTID相同的Grapphic
			   	for(var i=0;i<$gisObject.map.graphics.graphics.length;i++){
			      	var cGrapphic=$gisObject.map.graphics.graphics[i];
			      	if(cGrapphic.attributes
			      		&& cGrapphic.attributes[keyName]==objectid
			      		&& cGrapphic.attributes.$ispop && cGrapphic.attributes.$ispop==true
			      		&& cGrapphic.attributes.$searchName && cGrapphic.attributes.$searchName==searchName){
			         	graphic=cGrapphic;
			         	break;
			      	}
			   	}
			   	return graphic;
			},

			/**
			 * 获取查询的要素Graphic
			 */
			getGraphicByFeature : function(objectid, searchName) {
				var graphic = null;
				var keyName = $gisObject.searchParameter[searchName].keyName;
				if(keyName == null || keyName == ""){
					keyName = "OBJECTID";
				}
			   	//遍历地图的graphics查找OBJECTID和点击行的OBJECTID相同的Grapphic
			   	for(var i=0;i<$gisObject.map.graphics.graphics.length;i++){
			      	var cGrapphic=$gisObject.map.graphics.graphics[i];
			      	if(cGrapphic.attributes
			      		&& cGrapphic.attributes[keyName]==objectid
			      		&& cGrapphic.attributes.$isFeature && cGrapphic.attributes.$isFeature==true
			      		&& cGrapphic.attributes.$searchName && cGrapphic.attributes.$searchName==searchName){
			         	graphic=cGrapphic;
			         	break;
			      	}
			   	}
			   	return graphic;
			},

			/**
			 * 把度分秒的经纬度转换成度的经纬度
			 */
			DMSConvertToDegree : function(strcoordinateD, strcoordinateM,
					strcoordinateS) {
				if (!$itfreer_core.validateNum(strcoordinateD)
						|| !$itfreer_core.validateNum(strcoordinateM)
						|| !$itfreer_core.validateNum(strcoordinateS)) {
					return "";
				}
				icoordinateD = parseInt(strcoordinateD);
				icoordinateM = parseInt(strcoordinateM) / 60;
				icoordinateS = parseInt(strcoordinateS) / 3600;
				return icoordinateD + icoordinateM + icoordinateS;
			},

			// 放大
			mapZoomin : function(){
				// $gisObject.map.setMapCursor("default");
				if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
					$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/zoomin.cur),auto");
				}
				
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.activate(esri.toolbars.Navigation.ZOOM_IN);
				}
			},

			// 缩小
			mapZoomout : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
					$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/zoomout.cur),auto");
				}
				
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.activate(esri.toolbars.Navigation.ZOOM_OUT);
				}
			},

			// 平移
			mapPan : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
					$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/hand.cur),auto");
				}
				try{
					if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
						$gisObject.navToolbar.activate(esri.toolbars.Navigation.PAN);
					}
				}catch(e){
				}
			},

			// 全图
			mapFullextent : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.zoomToFullExtent();
				}
			},

			// 上一视图
			mapToprev : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.zoomToPrevExtent();
				}
			},

			// 下一视图
			mapTonext : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.zoomToNextExtent();
				}
			}
		};
		for(f in $itfreer_arcgis_core){
			$rootScope[f] = $itfreer_arcgis_core[f];
		}
		$rootScope.gisObject = $gisObject;
		return $itfreer_arcgis_core;
	});

	/**
	 * gis第一个控制器
	 */
	itfreerarcgiscoreModule.controller('gisFirstRouterCtrl', ['$scope', '$itfreerHttp', '$formObject', '$itfreer_form_core','$state','$wdp','$rootScope',
		function($scope,$itfreerHttp, $formObject, $itfreer_form_core,$state,$wdp,$rootScope){
			$formObject.isMIS = false;
			$itfreer_form_core.destroyForm();
			$itfreer_form_core.destroyEasyui();
		}
	]);

	/**
	 * gis最后一个控制器
	 */
	itfreerarcgiscoreModule.controller('gisLastRouterCtrl', ['$scope', '$itfreerHttp', '$formObject', '$itfreer_form_core',
		function($scope,$state,$itfreerHttp, $formObject, $itfreer_form_core){
			
		}
	]);

	/* 
	 * 加载服务器
	 */
	itfreerarcgiscoreModule.run(function($rootScope, $itfreer_arcgis_core, $gisObject) {
	  	
	});
}(window, angular));
/**itfreer.arcgis.draw.js**/
/* 
 * 定义itfreer.arcgis.draw绘制模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义ArcGIS的绘制模块
	 */
	var itfreerarcgisdrawModule = angular.module('itfreer.arcgis.draw', ['itfreer.arcgis.core']);

	/* 
	 * 定义ArcGIS的绘制模块
	 */
	itfreerarcgisdrawModule.factory('$itfreer_arcgis_draw', 
		function($rootScope, $itfreer_core, $itfreer_arcgis_core, $gisObject) {
			$itfreer_arcgis_draw = {
				/* 
				 * 绘制完成的事件
				 */
				onDrawEndEventFunction : null,

				/* 
				 * 初始化绘制工具
				 */
				init : function(){
					dojo.connect($gisObject.drawToolbars, "onDrawEnd", $itfreer_arcgis_draw.onDrawEnd);
				},

				/* 
				 * 绘制完成事件
				 */
				onDrawEnd : function(geometry){ 
					if($itfreer_arcgis_draw.onDrawEndEventFunction){
						$itfreer_arcgis_draw.onDrawEndEventFunction(geometry);
					}
				},

				/* 
				 * 获取点样式
				 */
				getPointSymbol : function(){ 
					// 点样式
					var pointSymbol = new esri.symbol.SimpleMarkerSymbol(
						esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 10,
						new esri.symbol.SimpleLineSymbol(
								esri.symbol.SimpleLineSymbol.STYLE_SOLID,
								new dojo.Color([
									$gisObject.styleConfig.drawStyle.strokeColor.r,
									$gisObject.styleConfig.drawStyle.strokeColor.g,
									$gisObject.styleConfig.drawStyle.strokeColor.b]), 1),
						new dojo.Color([$gisObject.styleConfig.drawStyle.fillColor.r,
								$gisObject.styleConfig.drawStyle.fillColor.g,
								$gisObject.styleConfig.drawStyle.fillColor.b,
								$gisObject.styleConfig.drawStyle.fillOpacity]));
					return pointSymbol;
				},

				/* 
				 * 获取线样式
				 */
				getLineSymbol : function(){ 
					// 线样式
					var lineSymbol = new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID,
						new dojo.Color([$gisObject.styleConfig.drawStyle.strokeColor.r,
								$gisObject.styleConfig.drawStyle.strokeColor.g,
								$gisObject.styleConfig.drawStyle.strokeColor.b,
								$gisObject.styleConfig.drawStyle.fillOpacity]), 2);
					return lineSymbol;
				},

				/* 
				 * 获取填充样式
				 */
				getFillSymbol : function(){ 
					// 面样式
					var fillSymbol = new esri.symbol.SimpleFillSymbol(
						esri.symbol.SimpleFillSymbol.STYLE_SOLID,
						this.lineSymbol, new dojo.Color([
								$gisObject.styleConfig.drawStyle.fillColor.r,
								$gisObject.styleConfig.drawStyle.fillColor.g,
								$gisObject.styleConfig.drawStyle.fillColor.b,
								$gisObject.styleConfig.drawStyle.fillOpacity]));
					return fillSymbol;
				},
				
				/* 
				 * 开始绘制点
				 */
				drawPoint : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['POINT']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制多点
				 */
				drawMultiPoint : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['MULTIPOINT']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制线段
				 */
				drawLine : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['LINE']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制线
				 */
				drawPolyline : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['POLYLINE']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制自由线
				 */
				drawFreehandPolyline : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['FREEHANDPOLYLINE']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制面
				 */
				drawPolygon : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['POLYGON']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制自由面
				 */
				drawFreehandPolygon : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['FREEHANDPOLYGON']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制箭头
				 */
				drawArrow : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['ARROW']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制三角形
				 */
				drawTriangle : function(){
					$itfreer_arcgis_core.mapPan(); 
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['TRIANGLE']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制圆形
				 */
				drawCircle : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['CIRCLE']);
						$gisObject.isDrawing=true;
					}
				},
				
				/* 
				 * 开始绘制椭圆
				 */
				drawEllipse : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['ELLIPSE']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 开始绘制Extent
				 */
				drawExtent : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/crosshair.cur),auto");
					}
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.activate(esri.toolbars.Draw['EXTENT']);
						$gisObject.isDrawing=true;
					}
				},

				/* 
				 * 结束绘制
				 */
				deDraw : function(){ 
					$itfreer_arcgis_core.mapPan();
					if(!$itfreer_core.isNullOrUndefined($gisObject.drawToolbars)){
						$gisObject.drawToolbars.deactivate();
						$gisObject.isDrawing=false;
					}
				},

				/* 
				 * 清除绘制结果
				 */
				clearGraphics : function(){
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)
						&& !$itfreer_core.isNullOrUndefined($gisObject.map.graphics)){
						$gisObject.map.graphics.clear();
					}
				},
		    
				/* 
				 * 结束绘制并清除绘制结果
				 */
				deDrawAndClearGraphics : function(){ 
					$itfreer_arcgis_draw.deDraw();
					$itfreer_arcgis_draw.clearGraphics();
					if($gisObject.map
						&& $gisObject.map.infoWindow){
						$gisObject.map.infoWindow.hide();
					}
				}
			};
			for(f in $itfreer_arcgis_draw){
				$rootScope[f] = $itfreer_arcgis_draw[f];
			}
			return $itfreer_arcgis_draw;
		}
	);

	/* 
	 * 加载服务器
	 */
	itfreerarcgisdrawModule.run(function($rootScope, $itfreer_arcgis_draw) {
	  	
	});
}(window, angular));
/**itfreer.arcgis.geometryservice.js**/
/* 
 * 定义itfreer.arcgis.geometryservice处理模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义ArcGIS geometry处理模块
	 */
	var itfreerarcgisGeometryserviceModule = angular.module('itfreer.arcgis.geometryservice', ['itfreer.arcgis.core']);

	/* 
	 * 定义ArcGIS geometry处理模块
	 */
	itfreerarcgisGeometryserviceModule.factory('$itfreer_arcgis_geometryservice', 
		function($rootScope, $itfreer_arcgis_core, $gisObject) {
			$itfreer_arcgis_geometryservice = {

				/* 
				 * 投影转换成功
				 */
				onProjectCompleteEventFunction : null,

				/* 
				 * 简单化成功
				 */
				onSimplifyCompleteEventFunction : null,

				/* 
				 * 长度计算成功
				 */
				onLengthsCompleteEventFunction : null,

				/* 
				 * 长度面积计算成功
				 */
				onAreasAndLengthsCompleteEventFunction : null,

				/* 
				 * 缓冲分析成功
				 */
				onBufferCompleteEventFunction : null,

				/* 
				 * 初始化
				 */
				init : function(){
					 //添加onProjectComplete完成后事件监听
				    dojo.connect($gisObject.geometryService, "onProjectComplete", $itfreer_arcgis_geometryservice.onProjectComplete);
				    dojo.connect($gisObject.geometryService, "onSimplifyComplete", $itfreer_arcgis_geometryservice.onSimplifyComplete);
				    dojo.connect($gisObject.geometryService, "onLengthsComplete", $itfreer_arcgis_geometryservice.onLengthsComplete);
			     	dojo.connect($gisObject.geometryService, "onAreasAndLengthsComplete", $itfreer_arcgis_geometryservice.onAreasAndLengthsComplete);
					dojo.connect($gisObject.geometryService, "onBufferComplete", $itfreer_arcgis_geometryservice.onBufferComplete);
				},

				/* 
				 * 投影转换成功
				 */
				onProjectComplete : function(graphics){
					if($itfreer_arcgis_geometryservice.onProjectCompleteEventFunction){
						$itfreer_arcgis_geometryservice.onProjectCompleteEventFunction(graphics);
					}
				},

				/* 
				 * 简单化成功
				 */
				onSimplifyComplete : function(graphics){
					if($itfreer_arcgis_geometryservice.onSimplifyCompleteEventFunction){
						$itfreer_arcgis_geometryservice.onSimplifyCompleteEventFunction(graphics);
					}
				},

				/* 
				 * 长度计算成功
				 */
				onLengthsComplete : function(graphics){
					if($itfreer_arcgis_geometryservice.onLengthsCompleteEventFunction){
						$itfreer_arcgis_geometryservice.onLengthsCompleteEventFunction(graphics);
					}
				},

				/* 
				 * 长度面积计算成功
				 */
				onAreasAndLengthsComplete : function(graphics){
					if($itfreer_arcgis_geometryservice.onAreasAndLengthsCompleteEventFunction){
						$itfreer_arcgis_geometryservice.onAreasAndLengthsCompleteEventFunction(graphics);
					}
				},

				/* 
				 * 缓冲分析成功
				 */
				onBufferComplete : function(graphics){
					if($itfreer_arcgis_geometryservice.onBufferCompleteEventFunction){
						$itfreer_arcgis_geometryservice.onBufferCompleteEventFunction(graphics);
					}
				},

				/* 
				 * 进行投影转换
				 */
				project : function(geometrys, outSR){
					// 进行投影转换，完成后调用projectComplete
				    var params = new esri.tasks.ProjectParameters();
					params.geometries = geometrys;
					params.outSR = outSR;
					$gisObject.geometryService.project(params);
				}, 

				/* 
				 * 长度计算
				 */
				lengths : function(geometrys){
					var lengthParams = new esri.tasks.LengthsParameters();
					lengthParams.polylines = geometrys;
					lengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_KILOMETER;
			     	$gisObject.geometryService.lengths(lengthParams);
				}, 

				/* 
				 * 长度面积计算
				 */
				areasAndLengths : function(geometrys){
					var areasAndLengthParams = new esri.tasks.AreasAndLengthsParameters();
					areasAndLengthParams.areaUnit = esri.tasks.GeometryService.UNIT_SQUARE_KILOMETERS;
					areasAndLengthParams.polygons = geometrys;
					// 进行面积测量
					$gisObject.geometryService.areasAndLengths(areasAndLengthParams);
				}, 

				/* 
				 * 简单化处理
				 */
				simplify : function(geometrys){
			     	$gisObject.geometryService.simplify(geometrys);
				},

				/* 
				 * 简单化处理
				 */
				buffer : function(distances, graphics){
					var params = new esri.tasks.BufferParameters();
					params.distances = [distances];
					// 做缓存，都使用投影坐标
					params.outSpatialReference = $gisObject.tywkid;
					params.bufferSpatialReference = $gisObject.tywkid;
					params.geometries = graphics;
					//buffer的单位，米
	   				params.unit = esri.tasks.BufferParameters.UNIT_METER;
					$gisObject.geometryService.buffer(params);
				}
			};
			for(f in $itfreer_arcgis_geometryservice){
				$rootScope[f] = $itfreer_arcgis_geometryservice[f];
			}
			return $itfreer_arcgis_geometryservice;
		}
	);

	/* 
	 * 加载服务器
	 */
	itfreerarcgisGeometryserviceModule.run(function($rootScope, $itfreer_arcgis_geometryservice) {
	  	
	});
}(window, angular));
/**itfreer.arcgis.locator.js**/
/* 
 * 定义itfreer.arcgis.locator定位器模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义ArcGIS定位器模块
	 */
	var itfreerarcgislocatorModule = angular.module('itfreer.arcgis.locator', ['itfreer.arcgis.core','itfreer.arcgis.geometryservice']);

	/* 
	 * 定义ArcGIS定位器模块
	 */
	itfreerarcgislocatorModule.factory('$itfreer_arcgis_locator', 
		function($rootScope, $itfreer_core, $itfreer_arcgis_core, 
			$itfreer_arcgis_geometryservice, $gisObject) {
			$itfreer_arcgis_locator = {
				/* 
				 * 当定位完成事件
				 */
				onAddressToLocationsCompleteEventFunction : null,

				/* 
				 * 初始化定位器
				 */
				init : function(){
					dojo.connect($gisObject.locator, "onAddressToLocationsComplete", this.onAddressToLocationsComplete);
				},

				/* 
				 * 当定位完成事件
				 */
				onAddressToLocationsComplete : function(candidate){
					var onFunction = $itfreer_arcgis_locator.onAddressToLocationsCompleteEventFunction 
						? $itfreer_arcgis_locator.onAddressToLocationsCompleteEventFunction 
						: $itfreer_arcgis_locator.defulatOnAddressToLocationsComplete;

					onFunction(candidate);
				},

				/* 
				 * 默认事件
				 */
				defulatOnAddressToLocationsComplete : function(candidate) {
		            if (candidate && candidate.length>0) {
		            	var adr = candidate[0];
		                var location = adr.location;
		                $rootScope.$apply(function() {
		            		$gisObject.locatorAddress = adr.address;
		            	});
		                var level = $gisObject.locatorLevel ? $gisObject.locatorLevel : 8;
		                $gisObject.map.centerAndZoom(location, level);
		            }
		        },

		        /* 
				 * 定位到指定名称的地址
				 */
				addressToLocations : function(name, level){
					if(!$itfreer_core.isNullOrUndefined($gisObject.locator)){
						$gisObject.locatorLevel = level;
						$gisObject.locator.addressToLocations({SingleKey:name});
					}
				},

				/* 
				 * 经纬度定位
				 */
				jwdLocator : function(){
					$itfreer_arcgis_draw.deDrawAndClearGraphics();

					var lonD = parseInt($gisObject.locatorParameter.jdd);
					var lonM = parseInt($gisObject.locatorParameter.jdf);
					var lonS = parseInt($gisObject.locatorParameter.jdm);
					var latD = parseInt($gisObject.locatorParameter.wdd);
					var latM = parseInt($gisObject.locatorParameter.wdf);
					var latS = parseInt($gisObject.locatorParameter.wdm);

					if (lonD > 180 || lonD < 0) {
						alert("【经度】:'度'范围 必须介于0~180之间,请重新输入");
						return;
					}
					if (latD > 90 || latD < 0) {
						alert("【纬度】:'度'范围必须介于0~90之间,请重新输入");
						return;
					}
					if (lonM > 60 || latM > 60 || lonM < 0 || latM < 0) {
						alert("'分' 范围必须介于0~60之间,请重新输入");
						return;
					}
					if (lonS > 60 || latS > 60 || lonS < 0 || latS < 0) {
						alert("'秒' 范围必须介于0~60之间,请重新输入");
						return;
					}

					var lon = $itfreer_arcgis_core.DMSConvertToDegree(lonD, lonM, lonS);
					var lat = $itfreer_arcgis_core.DMSConvertToDegree(latD, latM, latS);

					if (lat == "" || lon == "") {
						alert("请输入正确的经纬度");
						return;
					}

					var rPoint = new esri.geometry.Point();
					rPoint.x = lon;
					rPoint.y = lat;
					rPoint.spatialReference = $gisObject.dlwkid;

					// 如果是地理坐标，就直接定位
					if($gisObject.mapisdlwkid){
						$itfreer_arcgis_locator.coorLocation(rPoint);
					}else{
						// 先转换，再定位
						$itfreer_arcgis_geometryservice.onProjectCompleteEventFunction = function(graphics){
							$itfreer_arcgis_locator.coorLocation(graphics[0]);
						};
						$itfreer_arcgis_geometryservice.project([rPoint], $gisObject.tywkid);
					}
				},

				/* 
				 * 地理坐标定位
				 */
				dlLocator : function(){
					$itfreer_arcgis_draw.deDrawAndClearGraphics();
					
					var x = parseFloat($gisObject.locatorParameter.dlx);
					var y = parseFloat($gisObject.locatorParameter.dly);

					var rPoint = new esri.geometry.Point();
					rPoint.x = x;
					rPoint.y = y;
					rPoint.spatialReference = $gisObject.dlwkid;

					// 如果是地理坐标，就直接定位
					if($gisObject.mapisdlwkid){
						$itfreer_arcgis_locator.coorLocation(rPoint);
					}else{
						// 先转换，再定位
						$itfreer_arcgis_geometryservice.onProjectCompleteEventFunction = function(graphics){
							$itfreer_arcgis_locator.coorLocation(graphics[0]);
						};
						$itfreer_arcgis_geometryservice.project([rPoint], $gisObject.tywkid);
					}
				},

				/* 
				 * 平面坐标定位
				 */
				pmLocator : function(){
					$itfreer_arcgis_draw.deDrawAndClearGraphics();

					var x = parseFloat($gisObject.locatorParameter.pmx);
					var y = parseFloat($gisObject.locatorParameter.pmy);

					var rPoint = new esri.geometry.Point();
					rPoint.x = x;
					rPoint.y = y;
					rPoint.spatialReference = $gisObject.dlwkid;

					// 如果是地理坐标，先转换，再定位
					if($gisObject.mapisdlwkid){
						$itfreer_arcgis_geometryservice.onProjectCompleteEventFunction = function(graphics){
							$itfreer_arcgis_locator.coorLocation(graphics[0]);
						};
						$itfreer_arcgis_geometryservice.project([rPoint], $gisObject.dlwkid);
					}else{
						// 就直接定位
						$itfreer_arcgis_locator.coorLocation(rPoint);
					}
				},

				/* 
				 * 坐标定位
				 */
				coorLocation : function(rPoint){
					var _extent = $gisObject.fullExtent;
					if (!_extent.contains(rPoint)) {
						alert("坐标信息不在范围之内");
						return;
					}

					$gisObject.map.centerAndZoom(rPoint);

					// 设置小气泡
					var iconURL = getJsBasePath()+"/arcgis/images/Fore_3D_Menu_ZBDW.png";
					var pMark = new esri.symbol.PictureMarkerSymbol(iconURL, 25, 25);
					var _center = $itfreer_arcgis_core.getCenter(rPoint);
					var graphic = new esri.Graphic(_center, pMark);
					$gisObject.map.graphics.add(graphic);
				}
			};
			for(f in $itfreer_arcgis_locator){
				$rootScope[f] = $itfreer_arcgis_locator[f];
			}
			return $itfreer_arcgis_locator;
		}
	);

	/* 
	 * 加载服务器
	 */
	itfreerarcgislocatorModule.run(function($rootScope, $itfreer_arcgis_locator) {
	  	
	});
}(window, angular));
/**itfreer.arcgis.map.js**/
/* 
 * 定义itfreerArcgis模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义itfreerArcgis模块，用于map对象的初始化
	 */
	var itfreerarcgisModule = angular.module('itfreer.arcgis.map', 
		['itfreer.arcgis.draw',
		'itfreer.arcgis.geometryservice', 
		'itfreer.arcgis.locator', 
		'itfreer.arcgis.measure',
		'itfreer.arcgis.search',
		'itfreer.arcgis.book']);

	/**
	 * 定义核心模块依赖注入器，定义地图的基础用法
	 */
	itfreerarcgisModule.factory('$itfreer_arcgis_map',
		function($rootScope, $gisObject, $itfreer_core, $itfreer_arcgis_locator) {
			$itfreer_arcgis_map = {

				/**
				 * 设置政区服务
				 */
				setTiled : function(visible){
					for(attribute in $gisObject.BaseTiledLayer){
						if(visible){
							$gisObject.BaseTiledLayer[attribute].mapLayer.show();
						}else{
							$gisObject.BaseTiledLayer[attribute].mapLayer.hide();
						}
					} 
				},
				/**
				 * 返回视图
				 * **/
                 returnView:function(){
 			       	  $gisObject.map.setExtent($gisObject.fullExtent);
                 },
				/**
				 * 设置影像服务
				 */
				setImage : function(visible){
					for(attribute in $gisObject.BaseImageLayer){
						if(visible){
							$gisObject.BaseImageLayer[attribute].mapLayer.show();
						}else{
							$gisObject.BaseImageLayer[attribute].mapLayer.hide();
						}
					} 
				},

				/**
				 * 设置专题服务
				 */
				setServices : function(layer,isShow){
					if($gisObject.Services.hasOwnProperty(layer)){
						var visible = $gisObject.Services[layer].mapLayer.visible;
						visible = !visible;
						
						if(isShow != null){
							visible = isShow
						}

						if(visible){
							$gisObject.Services[layer].mapLayer.show();
						}else{
							$gisObject.Services[layer].mapLayer.hide();
						}
						return visible;
					}
				},
				
				/**
				 * 打印状态
				 */
				printStatus:{printing:false},
				
				/**
				 * 打印
				 */
				printImage : function() {
					if($gisObject.printingService){
						var template = new esri.tasks.PrintTemplate();
						template.exportOptions = { width: $gisObject.map.width, height: $gisObject.map.height, dpi: 96 };
						template.format = "PDF";
						template.layout = "MAP_ONLY";
						template.preserveScale = true;
						var params = new esri.tasks.PrintParameters();
						params.map = $gisObject.map;
						params.template = template;
						$itfreer_arcgis_map.printStatus.printing = true;
						$gisObject.printingService.execute(params, function(renderer) {
							if (renderer != null) {
								window.open(renderer.url);
							}
							$itfreer_arcgis_map.printStatus.printing = false;
						},function(error){
//							 $.messager.alert("错误", error.toString(),"error");
							 $itfreer_arcgis_map.printStatus.printing = false;
						});
					}
				}
			};
			for(f in $itfreer_arcgis_map){
				$rootScope[f] = $itfreer_arcgis_map[f];
			}
			return $itfreer_arcgis_map;
		}
	);

	/* 
	 * 定义arcgis map控件
	 */
	itfreerarcgisModule.directive('itfreerMap', 
		function($http, $gisObject,$itfreer_arcgis_locator, $itfreer_arcgis_geometryservice) {
		return {
			replace : true,
			restrict : 'E',
			template : '<div></div>',
			priority:99,
			link : function(scope, element, attrs, ctrl) {

				// 中心点
				var centerObject = eval(attrs.center);
				if(!centerObject){
					centerObject = [];
					centerObject.push(113.78279668);
					centerObject.push(22.6855779935);
				}

				var lods = eval(attrs.lods);
				if(!lods){
					lods = [
			             {"level" : 0, "resolution" : 1.40625, "scale" : 590995186.11750006},
			             {"level" : 1, "resolution" : 0.703125, "scale" : 295497593.05875003},
			             {"level" : 2, "resolution" : 0.3515625, "scale" : 147748796.52937502},
			             {"level" : 3, "resolution" : 0.17578125, "scale" : 73874398.264687508},
			             {"level" : 4, "resolution" : 0.087890625, "scale" : 36937199.132343754},
			             {"level" : 5, "resolution" : 0.0439453125, "scale" : 18468599.566171877},
			             {"level" : 6, "resolution" : 0.02197265625, "scale" : 9234299.7830859385},
			             {"level" : 7, "resolution" : 0.010986328125, "scale" : 4617149.8915429693},
			             {"level" : 8, "resolution" : 0.0054931640625, "scale" : 2308574.9457714846},
			             {"level" : 9, "resolution" : 0.00274658203125, "scale" : 1154287.4728857423},
			             {"level" : 10, "resolution" : 0.001373291015625, "scale" : 577143.73644287116},
			             {"level" : 11, "resolution" : 0.0006866455078125, "scale" : 288571.86822143558},
			             {"level" : 12, "resolution" : 0.00034332275390625, "scale" : 144285.93411071779},
			             {"level" : 13, "resolution" : 0.000171661376953125, "scale" : 72142.967055358895},
			             {"level" : 14, "resolution" : 0.0000858306884765625, "scale" : 36071.483527679447},
			             {"level" : 15, "resolution" : 0.0000429153442382812, "scale" : 18035.741763839724},
			             {"level" : 16, "resolution" : 0.0000214576721191406, "scale" : 9017.8708819198619},
			             {"level" : 17, "resolution" : 0.0000107288360595703, "scale" : 4508.9354409599309},
			             {"level" : 18, "resolution" : 5.36441802978515E-06, "scale" : 2254.4677204799655}
					];
				}else{
					var lodsCopy = [];
					lods.forEach(function(e){
						var item = {};
						item.level = parseInt(e.level);
						item.resolution = parseFloat(e.resolution);
						item.scale = parseFloat(e.scale);
						lodsCopy.push(item);
					});
					lods = lodsCopy;
				}

				var sliderlabels = eval(attrs.sliderlabels);
				if(!sliderlabels){
					sliderlabels = ["", "", "市 ", "县", "", "乡", "", "村", "", "", "", ""];
				}

				var zoom = 4;
				if(attrs.zoom){
					zoom = parseInt(attrs.zoom);
				}

				var maxZoom = 18;
				if(attrs.maxzoom){
					maxZoom = parseInt(attrs.maxzoom);
				}

				var minZoom = 0;
				if(attrs.minzoom){
					minZoom = parseInt(attrs.minzoom);
				}
				
				var slider = true;
				if(attrs.slider && attrs.slider=='true'){
					slider = true;
				}else{
					slider = false;
				}

				var initMap = function(){
					// 地理坐标系统
					if(attrs.dlwkid && attrs.dlwkid!=""){
						if($itfreer_core.validateNum(attrs.dlwkid)){
							var wkid = parseInt(attrs.dlwkid);
							$gisObject.dlwkid = new esri.SpatialReference({wkid: wkid});
						}else{
							$gisObject.dlwkid = new esri.SpatialReference(attrs.dlwkid);
						}
					}else{
						$gisObject.dlwkid = new esri.SpatialReference({wkid: 4326});
					}

					// 投影坐标系统
					if(attrs.tywkid && attrs.tywkid!=""){
						$gisObject.tywkid = parseInt(attrs.tywkid);
						if($itfreer_core.validateNum(attrs.tywkid)){
							var wkid = parseInt(attrs.tywkid);
							$gisObject.tywkid = new esri.SpatialReference({wkid: wkid});
						}else{
							$gisObject.tywkid = new esri.SpatialReference(attrs.tywkid);
						}
					}else{
						$gisObject.tywkid = new esri.SpatialReference({wkid: 102100});
					}

					// 当前的地图是否为地理坐标系统
					$gisObject.mapisdlwkid = true;
					if(attrs.mapisdlwkid && attrs.mapisdlwkid!=""){
						if(attrs.mapisdlwkid=="是"){
							$gisObject.mapisdlwkid = true;
						}else{
							$gisObject.mapisdlwkid = false;
						}
					}
					var wkid = null;
					if($gisObject.mapisdlwkid){
						wkid = $gisObject.dlwkid;
					}else{
						wkid = $gisObject.tywkid;
					}

					// 初始化地图
			        $gisObject.map = new esri.Map(attrs.id, {
						center : centerObject,
						sliderStyle : "large",
						lods : lods,
						sliderLabels : sliderlabels,
						zoom : true,
						maxZoom : attrs.maxzoom,
						minZoom : attrs.minzoom,
						logo : false,
						slider : true
					});
			        var scalebar = new esri.dijit.Scalebar({
			            map: $gisObject.map,
			            // "dual" displays both miles and kilometers
			            // "english" is the default, which displays miles
			            // use "metric" for kilometers
			            scalebarUnit: "metric"
			          });
			        if(attrs.initextent){
			        	var extentArray = attrs.initextent.split(",");
						var extent = new esri.geometry.Extent({
							"xmin" : parseFloat(extentArray[0]),
							"ymin" : parseFloat(extentArray[1]),
							"xmax" : parseFloat(extentArray[2]),
							"ymax" : parseFloat(extentArray[3]),
							"spatialReference" : wkid
						});
						$gisObject.fullExtent = extent;
						$gisObject.map.setExtent(extent);
			        }

					var layers = eval(attrs.layers);
					// {name:'bMapAnolayer',aliasName:'百度地图',group:'BaseImageLayer',mtype:'bMapAnolayer',url:'',visible:'是',showids:'0'}
					if(layers){
						layers.forEach(function(layer){
							var mapLayer = null;
							var visibleLayers = null;
							var layerName = layer.name;
							if(showids && showids!=""){
								visibleLayers = [];
								var ids = showids.split(",");
								ids.forEach(function(item){
									var intItem = parseInt(item);
									visibleLayers.push(intItem);
								});
							}

							if(layer.mtype == "ArcGISTiledMapServiceLayer"){
								// 瓦片地图服务
								mapLayer = new esri.layers.ArcGISTiledMapServiceLayer(layer.url,{id:layerName});
							} else if(layer.mtype == "ArcGISDynamicMapServiceLayer"){
								// 动态地图服务
								//set the image type to PNG24, note default is PNG8.
								var imageParameters = new esri.layers.ImageParameters();
						        imageParameters.format = "jpeg"; 
						        //Takes a URL to a non cached map service.
						        mapLayer = new esri.layers.ArcGISDynamicMapServiceLayer(layer.url, {
							        // "opacity" : 0.5,
							        "imageParameters" : imageParameters,
							        id:layerName,
							        visibleLayers: visibleLayers
						        });
							} else if(layer.mtype == "FeatureLayer"){
								// 要素服务
								mapLayer = new esri.layers.FeatureLayer(layer.url,{id:layerName});
							} else if(layer.mtype == "WMSLayer"){
								// WMS服务
								var showids = layer.showids;
								mapLayer = new esri.layers.WMSLayer(layer.url, {
						           format: "png",
						           id:layerName,
						           visibleLayers: visibleLayers
						        });
							} else if(layer.mtype == "WMTSLayer"){
								// WMTS服务
								var layerInfo = new esri.layers.WMTSLayerInfo({
						          	identifier: "opengeo:countries",
						          	tileMatrixSet: "EPSG:4326",
						          	format: "png"
						        });
						        var options = {
						          	serviceMode: "KVP",
						          	id:layerName,
						          	layerInfo: layerInfo
						        };
		        				mapLayer = new esri.layers.WMTSLayer(layer.url, options);
							} else if(layer.mtype == "ArcGISImageServiceLayer"){
								// 影像地图服务
								var params = new esri.layers.ImageServiceParameters();
						        params.noData = 0;
						        mapLayer = new esri.layers.ArcGISImageServiceLayer(layer.url, {
						          imageServiceParameters: params,
						          id:layerName,
						          opacity: 0.75
						        });
							} else if(layer.mtype == "bMapVeclayer"){
								// 百度地图政区服务
								mapLayer = this.arcGISObject.bmapVeclayer;
							} else if(layer.mtype == "bMapImglayer"){
								// 百度地图影像服务
								mapLayer = this.arcGISObject.bmapImglayer;
							} else if(layer.mtype == "bMapAnolayer"){
								// 百度地图标注服务
								mapLayer = this.arcGISObject.bmapAnolayer;
							} else if(layer.mtype == "tdMapAnnoLayer"){
								// 天地图基础地理标注服务
								mapLayer = this.arcGISObject.tdmapAnnoLayer;
							} else if(layer.mtype == "tdMapLayer"){
								// 天地图基础地理服务
								mapLayer = this.arcGISObject.tdmapLayer;
							} else if(layer.mtype == "tdMapImgAnnoLayer"){
								// 天地图影像标注服务
								mapLayer = this.arcGISObject.tdmapImgAnnoLayer;
							} else if(layer.mtype == "tdMapImgLayer"){
								// 天地图影像服务
								mapLayer = this.arcGISObject.tdmapImgLayer;
							}

							if(mapLayer){
								if(layer.visible != "是"){
									mapLayer.hide();
								}

								if(layer.group == "BaseTiledLayer"){
									// 政区服务
									$gisObject.BaseTiledLayer[layer.name] = {};
									$gisObject.BaseTiledLayer[layer.name].layer = layer;
									$gisObject.BaseTiledLayer[layer.name].mapLayer = mapLayer;
								} else if(layer.group == "BaseImageLayer"){
									// 影像服务
									$gisObject.BaseImageLayer[layer.name] = {};
									$gisObject.BaseImageLayer[layer.name].layer = layer;
									$gisObject.BaseImageLayer[layer.name].mapLayer = mapLayer;
								} else if(layer.group == "Services"){
									// 专题服务
									$gisObject.Services[layer.name] = {};
									$gisObject.Services[layer.name].layer = layer;
									$gisObject.Services[layer.name].mapLayer = mapLayer;
								}
								$gisObject.map.addLayer(mapLayer);
							}
						});
					}

					$gisObject.mapInit = true;
			        window.map = $gisObject.map;
			        // 初始化绘制对象
					$gisObject.navToolbar = new esri.toolbars.Navigation($gisObject.map);
					// 设置测量对象
		            $gisObject.drawToolbars = new esri.toolbars.Draw($gisObject.map);
		            $itfreer_arcgis_draw.init();
					//实例化GeometryService，地址为ags发布的GeometryServer
		            if(attrs.geometryservice && attrs.geometryservice!=""){
		            	$gisObject.geometryService = new esri.tasks.GeometryService(attrs.geometryservice);
		            	$itfreer_arcgis_geometryservice.init();
		            }
				};

				if(this.hasInitFinsh){
					initMap();
				}else{
					this.initFinshEvent = initMap;
				}
			}
		};
	});

	/* 
	 * 加载服务器
	 */
	itfreerarcgisModule.run(function($rootScope, $itfreer_arcgis_map) {
	  	
	});
}(window, angular));
/**itfreer.arcgis.measure.js**/
/* 
 * 定义itfreer.arcgis.measure测量模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义ArcGIS测量模块
	 */
	var itfreerArcgisMeasureModule = angular.module('itfreer.arcgis.measure', ['itfreer.arcgis.draw', 'itfreer.arcgis.geometryservice']);

	/* 
	 * 定义ArcGIS测量模块
	 */
	itfreerArcgisMeasureModule.factory('$itfreer_arcgis_measure', 
		function($rootScope, $gisObject, $itfreer_arcgis_core, $itfreer_core, 
			$itfreer_arcgis_draw, $itfreer_arcgis_geometryservice) {
			$itfreer_arcgis_measure = {

				/* 
				 * 显示测量距离
				 */
				onLengthsComplete : function(result, geometry){
				   	if (result && $gisObject.map.graphics != null) {

				   		var guid = $itfreer_core.getGUID();

				   		// 先添加绘制图形
						var symbol = $itfreer_arcgis_draw.getLineSymbol();
					    var graphic = new esri.Graphic(geometry, symbol);
					    if(!graphic.attributes){
							graphic.attributes = {};
						}
						graphic.attributes.$isLengthsComplete = true;
						graphic.attributes.$guid = guid;
					    $gisObject.map.graphics.add(graphic);

					    // 添加结果
						var resultStr = Number(result.lengths[0]).toFixed(3) + " 公里(关闭)";
						var font = new esri.symbol.Font("13px",
								esri.symbol.Font.STYLE_NORMAL,
								esri.symbol.Font.VARIANT_NORMAL,
								esri.symbol.Font.WEIGHT_BOLDER);
						var textSymbol = new esri.symbol.TextSymbol(resultStr, font, new dojo.Color([0, 0, 0]));
						var _center = $itfreer_arcgis_core.getCenter(geometry);
						var labelPointGraphic = new esri.Graphic(_center, textSymbol);
						if(!labelPointGraphic.attributes){
							labelPointGraphic.attributes = {};
						}
						labelPointGraphic.attributes.$isLengthsComplete = true;
						labelPointGraphic.attributes.$guid = guid;
						$gisObject.map.graphics.add(labelPointGraphic);
						
						// 启用map.graphics的鼠标事件
					    $gisObject.map.graphics.enableMouseEvents();
				       	dojo.connect($gisObject.map.graphics, "onClick", function (evt){
				    		var graphic = evt.graphic;
				    		if(!graphic.attributes){
					    		return;
					    	}

					    	if(graphic.attributes.$isLengthsComplete 
					    		&& graphic.attributes.$isLengthsComplete==true){
					    		var _guid = graphic.attributes.$guid;
					    		$gisObject.map.graphics.remove(graphic);

						    	//遍历地图的graphics查找guid一样的内容
							   	for(var i=0;i<$gisObject.map.graphics.graphics.length;i++){
							      	var cGrapphic=$gisObject.map.graphics.graphics[i];
							      	if(cGrapphic.attributes
							      		&& cGrapphic.attributes.$isLengthsComplete 
							      		&& cGrapphic.attributes.$isLengthsComplete==true
							      		&& cGrapphic.attributes.$guid==_guid){
							         	$gisObject.map.graphics.remove(cGrapphic);
							         	break;
							      	}
							   	}
					    	}
				    	});
					}
				},

				/* 
				 * 显示测量面积
				 */
				onAreasAndLengthsComplete : function(result, geometry){
				   	if (result && $gisObject.map.graphics != null) {

				   		var guid = $itfreer_core.getGUID();

				   		// 先添加绘制图形
					    var symbol = $itfreer_arcgis_draw.getFillSymbol();
					    var graphic = new esri.Graphic(geometry, symbol);
					    if(!graphic.attributes){
							graphic.attributes = {};
						}
						graphic.attributes.$isAreasAndLengthsComplete = true;
						graphic.attributes.$guid = guid;
					    $gisObject.map.graphics.add(graphic);

					    // 先添加绘制结果
						var resultStr = Number(result.areas[0]).toFixed(3) + "平方公里(单击关闭)";
						var font = new esri.symbol.Font("13px",
								esri.symbol.Font.STYLE_NORMAL,
								esri.symbol.Font.VARIANT_NORMAL,
								esri.symbol.Font.WEIGHT_BOLDER);
						var textSymbol = new esri.symbol.TextSymbol(resultStr, font,
								new dojo.Color([0, 0, 0]));
						var _center = $itfreer_arcgis_core.getCenter(geometry);
						var labelPointGraphic = new esri.Graphic(_center, textSymbol);
						if(!labelPointGraphic.attributes){
							labelPointGraphic.attributes = {};
						}
						labelPointGraphic.attributes.$isAreasAndLengthsComplete = true;
						labelPointGraphic.attributes.$guid = guid;
						$gisObject.map.graphics.add(labelPointGraphic);

						// 启用map.graphics的鼠标事件
					    $gisObject.map.graphics.enableMouseEvents();
				       	dojo.connect($gisObject.map.graphics, "onClick", function (evt){
				    		var graphic = evt.graphic;
				    		if(!graphic.attributes){
					    		return;
					    	}

					    	if(graphic.attributes.$isAreasAndLengthsComplete 
					    		&& graphic.attributes.$isAreasAndLengthsComplete==true){
					    		var _guid = graphic.attributes.$guid;
					    		$gisObject.map.graphics.remove(graphic);

						    	//遍历地图的graphics查找guid一样的内容
							   	for(var i=0;i<$gisObject.map.graphics.graphics.length;i++){
							      	var cGrapphic=$gisObject.map.graphics.graphics[i];
							      	if(cGrapphic.attributes
							      		&& cGrapphic.attributes.$isAreasAndLengthsComplete 
							      		&& cGrapphic.attributes.$isAreasAndLengthsComplete==true
							      		&& cGrapphic.attributes.$guid==_guid){
							         	$gisObject.map.graphics.remove(cGrapphic);
							         	break;
							      	}
							   	}
					    	}
				    	});
					}
				},

				/**
				 * 测试距离
				 * 
				 * @function {public} ?
				 */
				distance : function() {
					var drawGeometry = null;
					$itfreer_arcgis_draw.onDrawEndEventFunction = function(geometry){
						drawGeometry = geometry;
						$itfreer_arcgis_draw.deDraw();

					    // 如果是地理坐标系统，则先转换为投影坐标
					    if($gisObject.mapisdlwkid){
					    	$itfreer_arcgis_geometryservice.project([geometry], $gisObject.tywkid);
					    }else{
					    	$itfreer_arcgis_geometryservice.lengths([geometry]);
					    }
					};

					$itfreer_arcgis_geometryservice.onProjectCompleteEventFunction = function(graphics){
						$itfreer_arcgis_geometryservice.lengths([graphics[0]]);
					};
					
					$itfreer_arcgis_geometryservice.onLengthsCompleteEventFunction = function(result){
						$itfreer_arcgis_measure.onLengthsComplete(result, drawGeometry);
					};

					$itfreer_arcgis_geometryservice.onSimplifyCompleteEventFunction = null;
					$itfreer_arcgis_geometryservice.onAreasAndLengthsCompleteEventFunction = null;
					$itfreer_arcgis_geometryservice.onBufferCompleteEventFunction = null;

					$itfreer_arcgis_draw.drawPolyline();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/ruler.cur),auto");
					}
				},

				/**
				 * 测试面积
				 * 
				 * @function {public} ?
				 */
				area : function() {
					var drawGeometry = null;
					$itfreer_arcgis_draw.onDrawEndEventFunction = function(geometry){
						$itfreer_arcgis_draw.deDraw();
						drawGeometry = geometry;

					    // 如果是地理坐标系统，则先转换为投影坐标
					    if($gisObject.mapisdlwkid){
					    	$itfreer_arcgis_geometryservice.project([geometry], $gisObject.tywkid);
					    }else{
					    	// 如果为面类型需要先进行simplify操作在进行面积测算
						    $itfreer_arcgis_geometryservice.simplify([geometry]);
					    }
					};

					$itfreer_arcgis_geometryservice.onProjectCompleteEventFunction = function(graphics){
						// 如果为面类型需要先进行simplify操作在进行面积测算
					    $itfreer_arcgis_geometryservice.simplify([graphics[0]]);
					};

					$itfreer_arcgis_geometryservice.onSimplifyCompleteEventFunction = function(graphics){
						// 进行面积测量
						$itfreer_arcgis_geometryservice.areasAndLengths(graphics);
					};

					$itfreer_arcgis_geometryservice.onAreasAndLengthsCompleteEventFunction = function(result){
						$itfreer_arcgis_measure.onAreasAndLengthsComplete(result, drawGeometry);
					};

					$itfreer_arcgis_geometryservice.onLengthsCompleteEventFunction = null;
					$itfreer_arcgis_geometryservice.onBufferCompleteEventFunction = null;

					$itfreer_arcgis_draw.drawPolygon();
					if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
						$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/ruler.cur),auto");
					}
				}
			};
			for(f in $itfreer_arcgis_measure){
				$rootScope[f] = $itfreer_arcgis_measure[f];
			}
			return $itfreer_arcgis_measure;
		}
	);

	/* 
	 * 加载服务器
	 */
	itfreerArcgisMeasureModule.run(function($rootScope, $itfreer_arcgis_measure) {
	  	
	});
}(window, angular));
/**itfreer.arcgis.search.js**/
/* 
 * 定义itfreer.arcgis.search查询模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义ArcGIS查询模块
	 */
	var itfreerArcgisSearchModule = angular.module('itfreer.arcgis.search', ['itfreer.arcgis.draw', 'itfreer.arcgis.geometryservice']);

	/* 
	 * 定义ArcGIS查询模块
	 */
	itfreerArcgisSearchModule.factory('$itfreer_arcgis_search', 
		function($rootScope, $itfreer_form_core, $itfreer_arcgis_core, 
			$gisObject, $formObject,$http,
			$itfreer_arcgis_draw, $itfreer_arcgis_geometryservice) {
			$itfreer_arcgis_search = {

				/* 
				 * 定义ArcGIS查询模块
				 */
				getDefaultPointSyml : function(){ 
					// 点样式
					var pointSymbol = new esri.symbol.SimpleMarkerSymbol(
						esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 10,
						new esri.symbol.SimpleLineSymbol(
								esri.symbol.SimpleLineSymbol.STYLE_SOLID,
								new dojo.Color([
									255,10,10]), 1),
						new dojo.Color([250, 114, 114,
								$gisObject.styleConfig.highLightDefaultStyle.fillOpacity]));
					return pointSymbol;
				},

				/* 
				 * 定义默认选中样式
				 */
				getDefaultFillSyml : function(){ 
					// 线样式
					var outlineSyml = new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
							250, 11, 11,
							$gisObject.styleConfig.highLightDefaultStyle.fillOpacity]),
						$gisObject.styleConfig.highLightDefaultStyle.strokeWidth);

					// 面默认和选中样式
					var defaultFillSyml = new esri.symbol.SimpleFillSymbol(
						esri.symbol.SimpleFillSymbol.STYLE_SOLID, outlineSyml,
						new dojo.Color([250, 114, 114,
							$gisObject.styleConfig.highLightDefaultStyle.fillOpacity]));
					return defaultFillSyml;
				},

				/* 
				 * 定义ArcGIS查询模块
				 */
				getSelectPointSyml : function(){ 
					// 点样式
					var pointSymbol = new esri.symbol.SimpleMarkerSymbol(
						esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 15,
						new esri.symbol.SimpleLineSymbol(
								esri.symbol.SimpleLineSymbol.STYLE_SOLID,
								new dojo.Color([
									$gisObject.styleConfig.highLightSelectStyle.strokeColor.r,
									$gisObject.styleConfig.highLightSelectStyle.strokeColor.g,
									$gisObject.styleConfig.highLightSelectStyle.strokeColor.b]), 1),
						new dojo.Color([$gisObject.styleConfig.highLightSelectStyle.fillColor.r,
								$gisObject.styleConfig.highLightSelectStyle.fillColor.g,
								$gisObject.styleConfig.highLightSelectStyle.fillColor.b,
								$gisObject.styleConfig.highLightSelectStyle.fillOpacity]));
					return pointSymbol;
				},

				/* 
				 * 定义ArcGIS查询模块
				 */
				getSelectFillSyml : function(){ 
					// 点样式
					var pointSymbol = new esri.symbol.SimpleMarkerSymbol(
						esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 10,
						new esri.symbol.SimpleLineSymbol(
								esri.symbol.SimpleLineSymbol.STYLE_SOLID,
								new dojo.Color([
									$gisObject.styleConfig.highLightSelectStyle.strokeColor.r,
									$gisObject.styleConfig.highLightSelectStyle.strokeColor.g,
									$gisObject.styleConfig.highLightSelectStyle.strokeColor.b]), 1),
						new dojo.Color([$gisObject.styleConfig.highLightSelectStyle.fillColor.r,
								$gisObject.styleConfig.highLightSelectStyle.fillColor.g,
								$gisObject.styleConfig.highLightSelectStyle.fillColor.b,
								$gisObject.styleConfig.highLightSelectStyle.fillOpacity]));

					// 线样式
					var outlineSyml = new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
							$gisObject.styleConfig.highLightSelectStyle.strokeColor.r,
							$gisObject.styleConfig.highLightSelectStyle.strokeColor.g,
							$gisObject.styleConfig.highLightSelectStyle.strokeColor.b,
							$gisObject.styleConfig.highLightSelectStyle.fillOpacity]),
						$gisObject.styleConfig.highLightSelectStyle.strokeWidth);
			
					var selectFillSyml = new esri.symbol.SimpleFillSymbol(
						esri.symbol.SimpleFillSymbol.STYLE_SOLID, outlineSyml,
						new dojo.Color([$gisObject.styleConfig.highLightSelectStyle.fillColor.r,
							$gisObject.styleConfig.highLightSelectStyle.fillColor.g,
							$gisObject.styleConfig.highLightSelectStyle.fillColor.b,
							$gisObject.styleConfig.highLightSelectStyle.fillOpacity]));
					return selectFillSyml;
				},

				/**
				 * 初始化查询
				 */
				initSearch : function(searchName, setValue){
					$gisObject.searchParameter[searchName] = {
						// 查询的服务
						url : null,
						// 查询的字段
						selectFields : null,
						// 是否显示小汽泡
						showPop : true,
						// identify查询和find查询的ShowPop参数集
						showPops : {},
						// 是否高亮显示要素
						showFeature : true,
						// identify查询和find查询的ShowFeature参数集
						showFeatures : {},
						// 查询展示样式的标题
						infoTemplateTitle : '',
						// identify查询和find查询的infoTemplateTitle参数集
						infoTemplateTitles : {},
						// 查询展示样式的内容
						infoTemplateContent : '',
						// identify查询和find查询的infoTemplateContent参数集
						infoTemplateContents : {},
						// 查询展示窗口的宽
						infoWindowWidth : 240,
						// identify查询和find查询的infoWindowWidth参数集
						infoWindowWidths : {},
						// 查询展示窗口的高
						infoWindowHeiht : 120,
						// identify查询和find查询的infoWindowHeiht参数集
						infoWindowHeihts : {},
						// 空间查询类型 polygon, line, point
						type : null,
						// 空间查询缓存，单位米
						buffer : null,
						// 属性查询是否在当前的视图范围内
						extent : null,
						// 属性查询的属性参数
						attribute : {},
						// findtask的查询值
						searchText : '',
						// identify查询和find查询的图层IDs
						searchLayerIds : null,
						// 已经查询到的图层ids
						resultLayerIds : [],
						// 查询的分页大小
						searchPageSize : 5,
						// 查询展示样式
						infoTemplate : null,
						// 查询的分页大小
						searchPageIndex : 1,
						// 查询的总页数
						searchPageCount : 0,
						// 查询的总记录数
						searchRowCount : 0,
						// 查询结果列表
						searchResultList : null,
						// 查询的当前页列表
						searchPageList : null,
						// 是否显示查询面板
						searchPanel : true,
						// 是否对查询值做抽稀处理
						simple : false,
						// 是否对查询值做抽稀处理
						simples : [],
						//是否新建图层
						isNewLayer:false,
						//新建的图层
						graphicsLayer:null
					};
					if(setValue){
						$gisObject.searchParameter[searchName] = 
							jQuery.extend(true, $gisObject.searchParameter[searchName], setValue);
					}
					$itfreer_arcgis_draw.deDrawAndClearGraphics();
				},

				/**
				 * 初始化查询，如果存在数据之前的查询数据，则保留数据
				 */
				initSearchKO : function(searchName, setValue){
					if($gisObject.searchParameter[searchName]
						&& $gisObject.searchParameter[searchName].searchPageList
						&& $gisObject.searchParameter[searchName].searchPageList.length>0
						&& $gisObject.searchParameter[searchName].searchPanel==false){
						$itfreer_arcgis_search.showPageResults(searchName);
					}else{
				       	if($gisObject.searchParameter[searchName]
				       		&& $gisObject.searchParameter[searchName].resultLayerIds
				       		&& $gisObject.searchParameter[searchName].resultLayerIds.length>0){
				       		var firstLayerSearchName = $gisObject.searchParameter[searchName].resultLayerIds[0];
				       		$itfreer_arcgis_search.showPageResults(firstLayerSearchName);
				       	}else{
				       		$itfreer_arcgis_search.initSearch(searchName, setValue);
				       	}
					}
					if(setValue.onClick){
						$gisObject.searchParameter.onClick = setValue.onClick;
					}
					else{
						$gisObject.searchParameter.onClick = null;
					}
					if(setValue.getSymbol){
						$gisObject.searchParameter.getSymbol = setValue.getSymbol;
					}
					else{
						$gisObject.searchParameter.getSymbol = null;
					}
				},

			    /**
				 * 属性查询 不通过ArcGIS服务，直接调用自己写的后台
				 */
			    attributeSearchBy : function(searchName,queryObj){
			    	$itfreer_arcgis_draw.onDrawEndEventFunction = null;
					$itfreer_arcgis_geometryservice.onProjectCompleteEventFunction = null;
					$itfreer_arcgis_geometryservice.onSimplifyCompleteEventFunction = null;
					$itfreer_arcgis_geometryservice.onLengthsCompleteEventFunction = null;
					$itfreer_arcgis_geometryservice.onAreasAndLengthsCompleteEventFunction = null;
					$itfreer_arcgis_geometryservice.onBufferCompleteEventFunction = null;
					$itfreer_arcgis_draw.deDrawAndClearGraphics();

					var url = $gisObject.searchParameter[searchName].url;

		          	//信息模板
		          	$gisObject.searchParameter[searchName].infoTemplate = new esri.InfoTemplate();
		          	//设置Title
		          	var title = $gisObject.searchParameter[searchName].infoTemplateTitle;
		          	if(angular.isString(title))
		          		title = title.replace(/~/gm,'$');
		          	$gisObject.searchParameter[searchName].infoTemplate.setTitle(title);

		          	//设置Content
		          	var content = $gisObject.searchParameter[searchName].infoTemplateContent;
		          	if(angular.isString(content)){
		          		if(content.indexOf('<')==-1){
		          			var element = $('#'+content);
				          	if(element && element.length>0){
				          		content = element[0].innerHTML;
				          	}
		          		}
			          	content = content.replace(/~/gm,'$');
		          	}
		          	$gisObject.searchParameter[searchName].infoTemplate.setContent(content);
		          	
		          	
		          	//设置infoWindow的尺寸
		          	$gisObject.map.infoWindow.resize(
		          		$gisObject.searchParameter[searchName].infoWindowWidth, 
		          		$gisObject.searchParameter[searchName].infoWindowHeiht);

		          	
		          	//进行查询
		          	$http({
						method:"POST",
						url:getBasePath()+url,
						data:queryObj||{}
					}).success(function(wktRecords){
						//清除上一次的高亮显示
				       	$itfreer_arcgis_draw.deDrawAndClearGraphics();
				       	
				       	var results = {};
						var features = [];
						results.features = features;
						
						var spatialReference = $gisObject.map.spatialReference;
						var geometry;
						var row;
						var wkt ;
						var feature;
						if(wktRecords.data){
							for(var i=0;i<wktRecords.data.length;i++){
								 row = wktRecords.data[i];
								 wkt = row.WKT;
								 geometry = WKTUtil.read(wkt,spatialReference);
								 feature = new Object();
								 if(row.PHOTO)
									 row.PHOTO1 = row.PHOTO.substr(getBasePath().length);
								 feature.attributes = row;
								 feature.geometry = geometry;
								 features.push(feature);
							}
						}
				       	
			       		$gisObject.searchParameter[searchName].searchPanel = false;
			       		// 初始化查询结果
			       		$gisObject.searchResultList = results.features;
			       		$itfreer_arcgis_search.showSearchResultLRQ(results.features);
			       		//$itfreer_arcgis_search.initSearchResult(searchName, results.features);
					});
			    },
			    
			    /**
			     * lrq
			     */
			    showSearchResultLRQ : function(features){
			    	// 清除结果
			    	$itfreer_arcgis_draw.deDrawAndClearGraphics();

			    	//遍历查询结果
			       	//var pageList = $gisObject.searchParameter[searchName].searchPageList;
			    	var pageList = features;
			    	
			    	try{
				       	
				       	for (var i=0;i<pageList.length; i++){

				       		// 设置要素选中
				          	var feature = pageList[i];
				        	var symbol = $itfreer_arcgis_search.getDefaultPointSyml();
				        	
				        	if($gisObject.searchParameter.getSymbol){
				        		symbol = $gisObject.searchParameter.getSymbol(feature);
				        	}
					       
					       	feature.geometry.spatialReference = $gisObject.map.spatialReference;
							if(!feature.attributes){
								feature.attributes = {};
							}
							var showFeatureAttributesCopy = jQuery.extend(true, {}, feature.attributes);
							var showPopAttributesCopy = jQuery.extend(true, {}, feature.attributes);

							var graphic = new esri.Graphic(feature.geometry, symbol);
					
							graphic.defaultSymbol = symbol;
			          		graphic.attributes = showFeatureAttributesCopy;
							graphic.setInfoTemplate(null);
			          		
							if($gisObject.map.graphics){
			          			$gisObject.map.graphics.add(graphic);
			          		}
				       	}

				       	// 启用map.graphics的鼠标事件
				       	if($gisObject.map.graphics){
				       		$gisObject.map.graphics.enableMouseEvents();
				       	}
					    
					    dojo.disconnect( $gisObject.searchParameter.mouseOverHandle);
					    dojo.disconnect($gisObject.searchParameter.mouseOutHandle);
					    $gisObject.searchParameter.mouseOverHandle = 
					    	dojo.connect($gisObject.map.graphics, "onMouseOver", function (evt){
					    	var graphic = evt.graphic;
					    	if(!graphic.attributes){
					    		return;
					    	}
					    	$gisObject.map.setMapCursor("pointer");
							var pMark = new esri.symbol.PictureMarkerSymbol(getJsBasePath()+"/wdp/images/highlight.png", 25, 25);
							graphic.setSymbol(pMark);

					    });
					    $gisObject.searchParameter.mouseOutHandle = 
					    	dojo.connect($gisObject.map.graphics, "onMouseOut", function (evt){
					       	var graphic = evt.graphic;
					    	if(!graphic.attributes){
					    		return;
					    	}
					    	
					    	if($gisObject.currentSelectedFeature==graphic) return;
					    	
					    	$gisObject.map.setMapCursor("default");
					    	graphic.setSymbol(graphic.defaultSymbol);
					    });
				       	dojo.disconnect($gisObject.graphicsClickHandle);
				       	$gisObject.graphicsClickHandle = dojo.connect($gisObject.map.graphics, "onClick", function (evt){
				       		
				    		var graphic = evt.graphic;
				    		if(!graphic.attributes){
					    		return;
					    	}
				    		if(graphic.attributes.$guid) return;
				    		
				    		if($gisObject.searchParameter.onClick){
				    			$gisObject.searchParameter.onClick(graphic);
				    		}
				    	});
			    	}catch(e){
			    		console.log(e);
			    	}

			    	return pageList;
			    },
			    
			    /**
				 * 初始化查询的分页信息
				 */
			    initSearchResult : function (searchName, rows, noPageResults) {
			    	var rowCount = rows.length;
					if(rowCount<0){
						rowCount = 0;
					}
					var pageSize = $gisObject.searchParameter[searchName].searchPageSize;
					var pCount = rowCount / pageSize;
					pCount = parseInt(pCount);
					if((pageSize*pCount) < rowCount){
						pCount++;
					}
					// 查询的总页数
					$gisObject.searchParameter[searchName].searchPageCount = pCount;
					$gisObject.searchParameter[searchName].searchRowCount = rowCount;
					$gisObject.searchParameter[searchName].searchResultList = rows;
					
					//add by lrs,把结果在地图上显示出来
					$itfreer_arcgis_search.showPageResults(searchName);
					
					//把结果在列表中显示出来
					$itfreer_arcgis_search.setPageIndex(searchName, 1, noPageResults);
				},
				
				/**
				 * 显示分页查询结果
				 */
			    showPageResults : function(searchName){
			    	//这一句，在地图上显示查询结果
					var pageList = $itfreer_arcgis_search.innerShowPageResults(searchName);
			    	if($gisObject.searchParameter[searchName].simple == true && pageList.length>1000){
			    		// 地图是否缩放
				    	dojo.connect($gisObject.map, "onExtentChange", function (extent,delta, levelChange, lod){
				    		if(levelChange 
				    			&& $gisObject.searchParameter[searchName].simple){
				    			$itfreer_arcgis_search.innerShowPageResults(searchName);
				    		}
					    });
			    	}
			    	//设置地图视图范围
			       	var rExtent = $itfreer_arcgis_core.getMaxExtent(pageList);
			       	//$gisObject.map.setExtent(rExtent);
			    },
			    
			    innerShowPageResults : function(searchName){
			    	// 清除结果
			    	$itfreer_arcgis_draw.deDrawAndClearGraphics();

			    	//遍历查询结果
			       	//var pageList = $gisObject.searchParameter[searchName].searchPageList;
			    	var pageList = $gisObject.searchParameter[searchName].searchResultList;
			    	
			    	try{
			    		if($gisObject.searchParameter[searchName].simple == true && pageList.length>1000){
				       		pageList = $itfreer_arcgis_search.simple(pageList);
				       	}
				       	
				       	var infoTemplate = $gisObject.searchParameter[searchName].infoTemplate;
				    	var getSymbolFunction = $gisObject.searchParameter[searchName].getSymbol;
				       	
				       	for (var i=0;i<pageList.length; i++){

				       		// 设置要素选中
				          	var feature = pageList[i];
				          	feature.attributes.searchName = searchName;
				        	var symbol;
					       
					       	if(getSymbolFunction != null){
					       		symbol = getSymbolFunction(feature);
					       	}
					       	if(symbol == null ){
					       		symbol = $itfreer_arcgis_search.getDefaultFillSyml();
						       	if(pageList.length>0 && pageList[0].geometry.type == "point"){
						       		symbol = $itfreer_arcgis_search.getDefaultPointSyml();
						       	}
					       	}

					       	feature.geometry.spatialReference = $gisObject.map.spatialReference;
				          	var showFeature = $gisObject.searchParameter[searchName].showFeature;
				          	var showPop = $gisObject.searchParameter[searchName].showPop;
				          	var showWindows = $gisObject.searchParameter[searchName].showWindows;
							if(!feature.attributes){
								feature.attributes = {};
							}
							var showFeatureAttributesCopy = jQuery.extend(true, {}, feature.attributes);
							var showPopAttributesCopy = jQuery.extend(true, {}, feature.attributes);

				          	if(showFeature){
				          		showFeatureAttributesCopy.$searchName = searchName;
				          		showFeatureAttributesCopy.$isFeature = true;
								showFeatureAttributesCopy.$showFeature = showFeature;
								showFeatureAttributesCopy.$showPop = showPop;
								
								var graphic = new esri.Graphic(feature.geometry, symbol);
						
								graphic.defaultSymbol = symbol;
				          		graphic.attributes = showFeatureAttributesCopy;
				          		if(showWindows == false){
									graphic.setInfoTemplate(null);
								}
								else{
									graphic.setInfoTemplate(infoTemplate);
				          		}
				          		if($gisObject.map.graphics){
				          			$gisObject.map.graphics.add(graphic);
				          		}
				          	}
							
				          	if(showPop){
								showPopAttributesCopy.$searchName = searchName;
								showPopAttributesCopy.$ispop = true;
								showPopAttributesCopy.$popindxe = i;
								showPopAttributesCopy.$showFeature = showFeature;
								showPopAttributesCopy.$showPop = showPop;

							
								// 设置小气泡
								var iconName = "arrow";

								var iconURL = getJsBasePath()+"/arcgis/images/features/" + iconName + ".png";
								var pMark = new esri.symbol.PictureMarkerSymbol(iconURL, 25, 35);
								var _center = $itfreer_arcgis_core.getCenter(feature.geometry);
								var graphic = new esri.Graphic(_center, pMark);
								graphic.attributes = showPopAttributesCopy;
								
								if(showWindows == false){
									graphic.setInfoTemplate(null);
								}
								else{
									graphic.setInfoTemplate(infoTemplate);
				          		}
								if($gisObject.map.graphics){
				          			$gisObject.map.graphics.add(graphic);
				          		}
				          	}
				       	}

				       	// 启用map.graphics的鼠标事件
				       	if($gisObject.map.graphics){
				       		$gisObject.map.graphics.enableMouseEvents();
				       	}
					    
					    dojo.disconnect( $gisObject.searchParameter[searchName].mouseOverHandle);
					    dojo.disconnect($gisObject.searchParameter[searchName].mouseOutHandle);
					    $gisObject.searchParameter[searchName].mouseOverHandle = 
					    	dojo.connect($gisObject.map.graphics, "onMouseOver", function (evt){
					    	var graphic = evt.graphic;
					    	if(!graphic.attributes){
					    		return;
					    	}
					    	$gisObject.map.setMapCursor("pointer");
					    	if(graphic.attributes.$ispop && graphic.attributes.$ispop==true){
					    		$itfreer_arcgis_search.selectPopByGraphic(graphic,searchName);
					    	}

					    	if(graphic.attributes.$isFeature && graphic.attributes.$isFeature==true){
					    		$itfreer_arcgis_search.selectFeatureByGraphic(graphic,searchName);
					    	}
					    });
					    $gisObject.searchParameter[searchName].mouseOutHandle = 
					    	dojo.connect($gisObject.map.graphics, "onMouseOut", function (evt){
					       	var graphic = evt.graphic;
					    	if(!graphic.attributes){
					    		return;
					    	}
					    	
					    	if($gisObject.currentSelectedFeature==graphic) return;
					    	
					    	$gisObject.map.setMapCursor("default");
					    	if(graphic.attributes.$ispop && graphic.attributes.$ispop==true){
					    		$itfreer_arcgis_search.unSelectPopByGraphic(graphic,searchName);
					    	}
					    	
					    	if(graphic.attributes.$isFeature && graphic.attributes.$isFeature==true){
					    		$itfreer_arcgis_search.unSelectFeatureByGraphic(graphic,searchName);
					    	}
					    });
				       	dojo.disconnect($gisObject.graphicsClickHandle);
				       	$gisObject.graphicsClickHandle = dojo.connect($gisObject.map.graphics, "onClick", function (evt){
				       		
				       		alert("click me");
				    		var graphic = evt.graphic;
				    		if(!graphic.attributes){
					    		return;
					    	}
				    		if(graphic.attributes.$guid) return;
				    		
				    		if($gisObject.searchParameter[searchName].onClick){
				    			$gisObject.searchParameter[searchName].onClick(graphic);
				    		}
				    		
				    	});
			    	}catch(e){
			    		console.log(e);
			    	}

			    	return pageList;
			    },

				/**
				 * 周边搜索
				 */
				circle:null,
				neighborLayer:null,
				neighborSearch : function(searchname,searchObj,onClick,onComplete){
					if($itfreer_arcgis_search.neighborLayer==null) {
						$itfreer_arcgis_search.neighborLayer = new esri.layers.GraphicsLayer({id:"neighbor_layer"});
						$gisObject.map.addLayer($itfreer_arcgis_search.neighborLayer);
					}
					$itfreer_arcgis_search.neighborLayer.clear();
					var symbol = new esri.symbol.SimpleFillSymbol();
					var fillColor = esri.Color.fromHex("#4673cc").toRgb();
					fillColor.push(0.5);
					symbol.setColor(fillColor);
					
					var strokeColor = esri.Color.fromHex("#a3b1cc").toRgb();
					strokeColor.push(0.9);
					symbol.outline.setWidth(1).setColor(strokeColor);
					
					var pt = new esri.geometry.Point(Number(searchObj.geometry.x),Number(searchObj.geometry.y));
					pt.spatialReference = map.spatialReference;
					$itfreer_arcgis_search.circle = new esri.geometry.Circle({
			            center: pt,
			            radius: searchObj.radius,
			            radiusUnit: "esriKilometers"
			        });
					
					var graphic = new esri.Graphic($itfreer_arcgis_search.circle, symbol);
					$itfreer_arcgis_search.neighborLayer.add(graphic);
					
					
					// 实例化QueryTask
		          	var queryTask = new esri.tasks.QueryTask(searchObj.url);
		          	// 查询参数
		          	var query = new esri.tasks.Query();
					// 需要返回的字段 ["*"]
		          	query.outFields = ["*"];
		          	//需要返回Geometry
		          	query.returnGeometry = true;
		          	// 处理空间查询
		          	query.geometry = $itfreer_arcgis_search.circle;
					query.outSpatialReference = $gisObject.map.spatialReference;
					query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_CONTAINS;
					//关键字参数
					query.where = searchObj.where;

					//进行查询
		          	queryTask.execute(query, function (results){
				       	//清除上一次的高亮显示
//				       	$itfreer_arcgis_draw.deDrawAndClearGraphics();
				       	if(!results || results.features.length<=0){
				       		results = {};
				       		results.features = [];
				       	}
				       	$itfreer_arcgis_search.showResultOnLayer(searchname,$itfreer_arcgis_search.neighborLayer, results.features, onClick);
				       	
				       	if(onComplete){
				       		onComplete(results.features);
				       	}
				    });
				},
				
				showResultOnLayer:function(searchname,layer, features, onClick){
			       	if(features.length>1000){
			       		features = $itfreer_arcgis_search.simple(features);
			       	}
			       	
			       	for (var i=0;i<features.length; i++){
			          	var feature = features[i];
			        	var symbol;
				       	feature.geometry.spatialReference = $gisObject.map.spatialReference;
						if(!feature.attributes){
							feature.attributes = {};
						}
						var showFeatureAttributesCopy = jQuery.extend(true, {}, feature.attributes);
						showFeatureAttributesCopy.$searchName = searchname;
						// 设置小气泡
						var iconName = "arrow";
						var iconURL = getJsBasePath()+"/arcgis/images/features/" + iconName + ".png";
						var pMark = new esri.symbol.PictureMarkerSymbol(iconURL, 25, 35);
						var _center = $itfreer_arcgis_core.getCenter(feature.geometry);
						var graphic = new esri.Graphic(_center, pMark);
						graphic.attributes = showFeatureAttributesCopy;
						if(layer){
							layer.add(graphic);
		          		}
		          	}

			       	// 启用map.graphics的鼠标事件
			       	layer.enableMouseEvents();
			       	if($itfreer_arcgis_search.neighborLayerClickHandler){
			       		dojo.disconnect($itfreer_arcgis_search.neighborLayerClickHandler);
			       	}
			       	$itfreer_arcgis_search.neighborLayerClickHandler = dojo.connect(layer, "onClick", function (evt){
			    		var graphic = evt.graphic;
			    		if(!graphic.attributes){
				    		return;
				    	}
			    		if(graphic.attributes.$guid) return;
			    		
			    		if(onClick){
			    			onClick(graphic);
			    		}
			    	});

			    	return features;
			    },
			    
			    setMapFullExtent:function(){
			    	if($gisObject.map && $gisObject.fullExtent){
			    		$gisObject.map.setExtent($gisObject.fullExtent);
			    	}
			    },
			    
			    /**
			     * 获取要素的范围
			     */
			    getExentByFeatures:function(url,where,onSuccess){
			    	// 实例化QueryTask
		          	var queryTask = new esri.tasks.QueryTask(url);
		          	// 查询参数
		          	var query = new esri.tasks.Query();
					// 需要返回的字段 ["*"]
		          	query.outFields = ["*"];
		          	//需要返回Geometry
		          	query.returnGeometry = true;
		          	// 处理空间查询
					//关键字参数
					query.where = where;

					//进行查询
		          	queryTask.execute(query, function (results){
				       	if(!results || results.features.length<=0){
				       		return;
				       	}
				    	var extent = $itfreer_arcgis_core.getMaxExtent(results.features);
//				       	var extent = results.features[0].geometry.getExtent();
//				       	for (var i=0;i<results.features.length;i++)
//				       	{
//				       		extent = extent.union(results.features[i].geometry.getExtent());
//				       	}
				       	if(onSuccess && extent){
				       		onSuccess(extent);
				       	}
				    });
			    },
			    
				/* 
				 * 处理buffer的情况
				 */
				optionBuffer : function(geometry, searchName, identify){
					var buffer = $gisObject.searchParameter[searchName].buffer;
					var mapisdlwkid = $gisObject.mapisdlwkid;

					if(buffer && buffer!="" && buffer!="0"){
						// 先做buffer
						var distances = parseInt(buffer);
						if(distances>0){
							// 如果为地理坐标，则先转换平面，再做缓存
							if(mapisdlwkid){
								$itfreer_arcgis_geometryservice.project([geometry], $gisObject.tywkid);
							}else{
								$itfreer_arcgis_geometryservice.buffer(distances, [geometry]);
							}
						}else{
							// 内部查询
							if(identify){
								$itfreer_arcgis_search.innerIdentifySearch(searchName, geometry);
							}else{
								$itfreer_arcgis_search.innerSpaceSearch(searchName, geometry);
							}
						}
					}else{
						// 内部查询
						if(identify){
							$itfreer_arcgis_search.innerIdentifySearch(searchName, geometry);
						}else{
							$itfreer_arcgis_search.innerSpaceSearch(searchName, geometry);
						}
					}
				},

				/* 
				 * 对象simplify完成后调用方法
				 */
				onSimplifyComplete : function(graphics, searchName){
					$itfreer_arcgis_search.optionBuffer(graphics[0], searchName);
				},

				/* 
				 * 对象投影转换后
				 */
				onProjectComplete  : function(graphics, searchName, identify){
					var mapisdlwkid = $gisObject.mapisdlwkid;
					if(!mapisdlwkid){
						return;
					}

					// 如果是投影坐标，则做Buffer
					if(graphics[0].spatialReference.wkid == $gisObject.tywkid){
						var buffer = $gisObject.searchParameter[searchName].buffer;
						var distances = parseInt(buffer);
						$itfreer_arcgis_geometryservice.buffer(distances, graphics);
					} else if(graphics[0].spatialReference.wkid == $gisObject.dlwkid){
						// 临时显示缓冲区
						var symbol = $itfreer_arcgis_search.getSelectFillSyml();
				       	if(graphics[0].geometry.type == "point"){
				       		symbol = $itfreer_arcgis_search.getSelectPointSyml();
				       	}

						var graphic = new esri.Graphic(graphics[0], symbol);
						if($gisObject.map.graphics){
							$gisObject.map.graphics.add(graphic);
						}

			          	// 等待1.5秒
			          	setTimeout(function(){
							// 如果是地理从标，则查询
							if(identify){
								$itfreer_arcgis_search.innerIdentifySearch(searchName, graphics[0]);
							}else{
								$itfreer_arcgis_search.innerSpaceSearch(searchName, graphics[0]);
							}
			          	},900); 
					}
				},

				/* 
				 * 对象缓冲分析完成
				 */
				onBufferComplete : function (geometries, searchName, identify) {
					var mapisdlwkid = $gisObject.mapisdlwkid;

					if(mapisdlwkid){
						// 如果是地理坐标，需要将投影转换为地理
						$itfreer_arcgis_geometryservice.project(geometries, $gisObject.dlwkid);
					}else{
						// 临时显示缓冲区
						var symbol = $itfreer_arcgis_search.getSelectFillSyml();
				       	if(geometries[0].geometry.type == "point"){
				       		symbol = $itfreer_arcgis_search.getSelectPointSyml();
				       	}
						var graphic = new esri.Graphic(geometries[0], symbol);
						if($gisObject.map.graphics){
							$gisObject.map.graphics.add(graphic);
						}

			          	// 等待1.5秒
			          	setTimeout(function(){
							// 如果是地理从标，则查询
							if(identify){
								$itfreer_arcgis_search.innerIdentifySearch(searchName, geometries[0]);
							}else{
								$itfreer_arcgis_search.innerSpaceSearch(searchName, geometries[0]);
							}
			          	},900); 
					}
				},

 				/**
				 * 获取属性查询条件
				 */
			    getWhereString : function(searchName){
			    	var attribute = $gisObject.searchParameter[searchName].attribute;
			    	if(!attribute){
			    		return "";
			    	}

					var whereString = "";
		    		for(key in attribute){ 
						var fields = key.split(":");
						var field = null;
						var option = null;
						if (fields.length == 2) {
							field = fields[0];
							option = fields[1];
						} else {
							field = key;
							option = "=";
						}
						var value = attribute[key];

						if(value!=""){
							if (option=="=") {
								if (value==("\"null\"")) {
									whereString += field + " is null and ";
								} else {
									if(typeof value == "string"){
										whereString += field + " = '"+value+"' and ";
									}
									else{
										whereString += field + " = "+value+" and ";
									}
								}
							} else if (option==">") {
								whereString += field + " > "+value+" and ";
							} else if (option=="!=") {
								whereString += field + " != '"+value+"' and ";
							} else if (option==">=") {
								whereString += field + " >= "+value+" and ";
							} else if (option=="<") {
								whereString += field + " < "+value+" and ";
							} else if (option=="<=") {
								whereString += field + " <= "+value+" and ";
							} else if (option=="in") {
								whereString += field + " in (" + value.toString() + ") and ";
							} else if (option=="nin") {
								whereString += field + " not in (" + value.toString() + ") and ";
							} else if (option=="isnull") {
								whereString += field + " is null and ";
							} else if (option=="isnnull") {
								whereString += field + " is not null and ";
							} else if (option=="like") {
								whereString += field + " like '" + value.toString() + "' and ";
							} else if (option=="%like") { 
								whereString += field + " like '%" + value.toString() + "' and ";
							} else if (option=="like%") { 
								whereString += field + " like '" + value.toString() + "%' and ";
							}
						}
					}
					if(whereString!=""){
						whereString = whereString.substring(0, whereString.length-4);
					}
					return whereString;
			    },

			    setConfig : function(layerSearchName, searchName){
			    	$gisObject.searchParameter[layerSearchName] = {};
       				$gisObject.searchParameter[layerSearchName].searchPageSize = $gisObject.searchParameter[searchName].searchPageSize;
       				var identifyShowFeature = $gisObject.searchParameter[searchName].showFeatures;
       				if(identifyShowFeature 
       					&& identifyShowFeature.hasOwnProperty(layerSearchName)){
       					$gisObject.searchParameter[layerSearchName].showFeature = identifyShowFeature[layerSearchName];
       				}else{
       					$gisObject.searchParameter[layerSearchName].showFeature = $gisObject.searchParameter[searchName].showFeature;
       				}

       				var identifyShowPop = $gisObject.searchParameter[searchName].showPops;
       				if(identifyShowPop 
       					&& identifyShowPop.hasOwnProperty(layerSearchName)){
       					$gisObject.searchParameter[layerSearchName].showPop = identifyShowPop[layerSearchName];
       				}else{
       					$gisObject.searchParameter[layerSearchName].showPop = $gisObject.searchParameter[searchName].showPop;
       				}

       				var defaultTitle = $gisObject.searchParameter[searchName].infoTemplateTitle;
       				var infoTemplateTitles = $gisObject.searchParameter[searchName].infoTemplateTitles;
       				if(infoTemplateTitles 
       					&& infoTemplateTitles.hasOwnProperty(layerSearchName)){
       					$gisObject.searchParameter[layerSearchName].infoTemplateTitle = infoTemplateTitles[layerSearchName];
       				}else{
       					$gisObject.searchParameter[layerSearchName].infoTemplateTitle = defaultTitle;
       				}

       				var infoTemplateContents = $gisObject.searchParameter[searchName].infoTemplateContents;
       				if(infoTemplateContents 
       					&& infoTemplateContents.hasOwnProperty(layerSearchName)){
       					$gisObject.searchParameter[layerSearchName].infoTemplateContent = infoTemplateContents[layerSearchName];
       				}else{
       					$gisObject.searchParameter[layerSearchName].infoTemplateContent = "";
       				}

					var infoWindowWidths = $gisObject.searchParameter[searchName].infoWindowWidths;
       				if(infoWindowWidths 
       					&& infoWindowWidths.hasOwnProperty(layerSearchName)){
       					$gisObject.searchParameter[layerSearchName].infoWindowWidth = infoWindowWidths[layerSearchName];
       				}else{
       					$gisObject.searchParameter[layerSearchName].infoWindowWidth = $gisObject.searchParameter[searchName].infoWindowWidth;
       				}

       				var infoWindowHeihts = $gisObject.searchParameter[searchName].infoWindowHeihts;
       				if(infoWindowHeihts 
       					&& infoWindowHeihts.hasOwnProperty(layerSearchName)){
       					$gisObject.searchParameter[layerSearchName].infoWindowHeiht = infoWindowHeihts[layerSearchName];
       				}else{
       					$gisObject.searchParameter[layerSearchName].infoWindowHeiht = $gisObject.searchParameter[searchName].infoWindowHeiht;
       				}

       				//信息模板
		          	$gisObject.searchParameter[layerSearchName].infoTemplate = new esri.InfoTemplate();
		          	//设置Title
		          	var title = $gisObject.searchParameter[layerSearchName].infoTemplateTitle;
		          	if(!title){
		          		title = '';
		          	}
		          	title = title.replace(/~/gm,'$');
		          	$gisObject.searchParameter[layerSearchName].infoTemplate.setTitle(title);

		          	//设置Content
		          	var contentId = $gisObject.searchParameter[layerSearchName].infoTemplateContent;
		          	var content = '';
		          	if(contentId && contentId!=''){
		          		var element = $('#'+contentId);
			          	if(element && element.length>0){
			          		content = element[0].innerHTML;
			          	}
		          	}
		          	if(content == null || content == ""){
		          		content = '<b>OBJECTID: </b>~{OBJECTID}';
		          	}
		          	content = content.replace(/~/gm,'$');
		          	$gisObject.searchParameter[layerSearchName].infoTemplate.setContent(content);
		          	//设置infoWindow的尺寸
		          	$gisObject.map.infoWindow.resize(
		          		$gisObject.searchParameter[layerSearchName].infoWindowWidth, 
		          		$gisObject.searchParameter[layerSearchName].infoWindowHeiht);

		          	var simples = $gisObject.searchParameter[searchName].simples;
       				if(simples && simples.hasOwnProperty(layerSearchName)){
       					$gisObject.searchParameter[layerSearchName].simple = simples[layerSearchName];
       				}else{
       					$gisObject.searchParameter[layerSearchName].simple = $gisObject.searchParameter[searchName].simple;
       				}
			    },

			    /**
				 * identify中是否包含指定的图层
				 */
			    hasLayer : function(searchName, layerName){
			    	var layerSearchName = searchName + "_" + layerName;
			    	if($gisObject.searchParameter[searchName].resultLayerIds){
			    		var index = $gisObject.searchParameter[searchName].resultLayerIds.indexOf(layerSearchName);
			    		if(index>=0){
			    			return true;
			    		}else{
			    			return false;
			    		}
			    	}else{
			    		return false;
			    	}
			    },

				isContant : function(featureList, targetfeature, buf){
					var targetCenterPoint = $itfreer_arcgis_core.getCenter(targetfeature.geometry);
					for(var j=0;j<featureList.length;j++){
						var currentCenterPoint = $itfreer_arcgis_core.getCenter(featureList[j].geometry);
						if(Math.abs(targetCenterPoint.x - currentCenterPoint.x) <= buf && 
								Math.abs(targetCenterPoint.y - currentCenterPoint.y) <= buf){
							return false;
						}
					}
					return true;
				},

				/**
				 * 设置分页索引并且重新计算数据
				 */
				setPageIndex : function(searchName, pageIndex, noPageResults){
					$gisObject.searchParameter[searchName].searchPageIndex = pageIndex;
					$gisObject.searchParameter[searchName].searchPageList = [];
					if($gisObject.searchParameter[searchName].searchRowCount<=0){
						return;
					}

					var pageSize = $gisObject.searchParameter[searchName].searchPageSize;
					var endIndex = pageIndex * pageSize;
					var beginIndex = endIndex - pageSize;

					if(beginIndex > $gisObject.searchParameter[searchName].searchRowCount -1){
						return;
					}

					if(endIndex>$gisObject.searchParameter[searchName].searchRowCount){
						endIndex=$gisObject.searchParameter[searchName].searchRowCount;
					}

					for(var i=beginIndex;i<endIndex;i++){
						var obj = $gisObject.searchParameter[searchName].searchResultList[i];
						$gisObject.searchParameter[searchName].searchPageList.push(obj);
						if(i==beginIndex){
							
							var currentSelectedFeature = $gisObject.currentSelectedFeature;
							if(!currentSelectedFeature){
								$gisObject.currentSelectedFeature  = obj;
								currentSelectedFeature = obj;
							}
							$gisObject.currentSelectedFeature  = obj;
							if(obj!=currentSelectedFeature){
								$itfreer_arcgis_search.unSelectFeature(currentSelectedFeature.attributes.OBJECTID,'station');
							}
							$itfreer_arcgis_search.selectFeature($gisObject.currentSelectedFeature.attributes.OBJECTID,'station');
						}
					}
					if(noPageResults && noPageResults==true){
						return;
					}else{
						//commented by lrs
						//$itfreer_arcgis_search.showPageResults(searchName);
					}
				},
				
				/**
				 * 上一页
				 */
				preGisPage : function(searchName){
					var pageIndex = $gisObject.searchParameter[searchName].searchPageIndex;
					pageIndex--;
					if(pageIndex<=0){
						pageIndex =1 ;
					}
					$itfreer_arcgis_search.setPageIndex(searchName, pageIndex);
				},
				
				/**
				 * 下一页
				 */
				nextGisPage : function(searchName){
					var pageIndex = $gisObject.searchParameter[searchName].searchPageIndex;
					var pageCount = $gisObject.searchParameter[searchName].searchPageCount;
					pageIndex++;
					if(pageIndex>pageCount){
						pageIndex = pageCount ;
					}
					$itfreer_arcgis_search.setPageIndex(searchName, pageIndex);
				},
				
				/**
				 * 首页
				 */
				firstGisPage : function(searchName){
					$itfreer_arcgis_search.setPageIndex(searchName, 1);
				},
				
				/**
				 * 尾页
				 */
				lastGisPage : function(searchName){
					var pageCount = $gisObject.searchParameter[searchName].searchPageCount;
					$itfreer_arcgis_search.setPageIndex(searchName, pageCount);
				},

			    /**
				 * 高亮选中小气泡
				 */
			    selectPop : function(objectid, searchName){
			    	var graphic = $itfreer_arcgis_core.getGraphicByPop(objectid, searchName);
				   	if(!graphic){
				   		return;
				   	}
				   	$itfreer_arcgis_search.selectPopByGraphic(graphic,searchName);
			    },

			    /**
				 * 高亮选中小气泡
				 */
			    selectPopByGraphic : function(graphic,searchName){
				   	if(!graphic){
				   		return;
				   	}

				   	// 如果是自定义小气泡
			    	var i = graphic.attributes.$popindxe;
			    	// 设置小气泡
					var iconName = "arrow";
					var iconURL = getJsBasePath()+"/wdp/images/highlight.png";
					var pMark = new esri.symbol.PictureMarkerSymbol(iconURL, 20, 20);
					graphic.setSymbol(pMark);
			    },

			    /**
				 * 取消高亮选中小气泡
				 */
			    unSelectPop : function(objectid, searchName){
			    	var graphic = $itfreer_arcgis_core.getGraphicByPop(objectid, searchName);
				   	if(!graphic){
				   		return;
				   	}
				   	$itfreer_arcgis_search.unSelectPopByGraphic(graphic,searchName);
			    },

			    /**
				 * 取消高亮选中小气泡
				 */
			    unSelectPopByGraphic : function(graphic,searchName){
				   	if(!graphic){
				   		return;
				   	}
				   	
				   	// 如果是自定义小气泡
			    	var i = graphic.attributes.$popindxe;
			    	var iconName = "arrow";
//					if(i<=9){
//						iconName = i.toString();
//					}
					var iconURL = getJsBasePath()+"/arcgis/images/features/" + iconName + ".png";
					var pMark = new esri.symbol.PictureMarkerSymbol(iconURL, 25, 35);
					graphic.setSymbol(pMark);
			    },

			    /**
				 * 高亮选中查询要素
				 */
			    selectFeature : function(objectid, searchName){
			    	try{
			    		var graphic = $itfreer_arcgis_core.getGraphicByFeature (objectid, searchName);
			    		if(!graphic){
			    			return;
			    		}
			    		$itfreer_arcgis_search.selectFeatureByGraphic(graphic,searchName);
			    	}catch(e){
			    		console.log(e);
			    	}
			    },

			    /**
				 * 高亮选中查询要素
				 */
			    selectFeatureByGraphic : function(graphic,searchName){
				   	if(!graphic){
				   		return;
				   	}
				   	var getSymbolFunction = $gisObject.searchParameter[searchName].getSelectedSymbol;
				   	if(getSymbolFunction != null){
			       		symbol = getSymbolFunction(graphic);
			       	}
			       	if(symbol == null ){
			       		symbol = $itfreer_arcgis_search.getSelectFillSyml();
				       	if(graphic.geometry.type == "point"){
				       		symbol = $itfreer_arcgis_search.getSelectPointSyml();
				       	}
			       	}
			       	if(graphic.getShape()!=null){
			       		graphic.getShape().moveToFront();
			       	}
					graphic.setSymbol(symbol);
			    },

			    /**
				 * 取消高亮选中查询要素
				 */
			    unSelectFeature : function(objectid, searchName){
			    	var graphic = $itfreer_arcgis_core.getGraphicByFeature (objectid, searchName);
				   	if(!graphic){
				   		return;
				   	}
					$itfreer_arcgis_search.unSelectFeatureByGraphic(graphic, searchName);
			    },

			    /**
				 * 取消高亮选中查询要素
				 */
			    unSelectFeatureByGraphic : function(graphic,searchName){
				   	if(!graphic){
				   		return;
				   	}
				   	
				   	if($gisObject.currentSelectedFeature.attributes.OBJECTID==graphic.attributes.OBJECTID){
				   		return;
				   	} 
				   	
				   	var symbol = graphic.defaultSymbol;
				   	if(symbol == null){
				   		symbol = $itfreer_arcgis_search.getDefaultFillSyml();
				       	if(graphic.geometry.type == "point"){
				       		symbol = $itfreer_arcgis_search.getDefaultPointSyml();
				       	}
				   	}
					graphic.setSymbol(symbol);
					
					if(graphic.getShape()!=null){
			       		graphic.getShape().moveToBack();
			       	}
			    },

			    /**
				 * 显示详细信息窗口
				 */
			    showInfoWindowByPop : function (objectid, searchName){
			    	var graphic = $itfreer_arcgis_core.getGraphicByPop(objectid, searchName);
				   	if(!graphic){
				   		return false;
				   	}
			    	$itfreer_arcgis_search.showInfoWindowByGraphic(graphic);
			    	return true;
			    },

			    /**
				 * 显示详细信息窗口
				 */
			    showInfoWindowByFeature : function (objectid, searchName){
			    	var graphic = $itfreer_arcgis_core.getGraphicByFeature(objectid, searchName);
				   	if(!graphic){
				   		return false;
				   	}
				   	$itfreer_arcgis_search.showInfoWindowByGraphic(graphic);
				   	return true;
			    },

			    /**
				 * 显示详细信息窗口
				 */
			    showInfoWindow : function(objectid, searchName){
			    	if($itfreer_arcgis_search.showInfoWindowByPop(objectid, searchName)){
			    		return true;
			    	}else if($itfreer_arcgis_search.showInfoWindowByFeature(objectid, searchName)){
			    		return true;
			    	}
			    	return false;
			    },

			    /**
				 * 显示详细信息窗口
				 */
			    showInfoWindowByGraphic : function (graphic){
				   	if(!graphic){
				   		return;
				   	}

			       	var _extent = $itfreer_arcgis_core.getCenter(graphic.geometry);
			       	$gisObject.map.infoWindow.show(_extent);
			    },

			    /**
				 * 绽放到
				 */
			    setGraphicExtent : function(objectid, searchName){
			    	var graphic = $itfreer_arcgis_core.getGraphicByFeature(objectid, searchName);
				   	if(!graphic){
				   		return;
				   	}

					//设置地图视图范围
				   	if(graphic.geometry.type == "point"){
				   		$gisObject.map.centerAt(graphic.geometry);
				   		return;
			       	}
			       	var rExtent = $itfreer_arcgis_core.getMaxExtent([graphic]);
			    	$gisObject.map.setExtent(rExtent);
			    },
			    
			    /**
				 * 绽放到
				 */
			    setGraphicExtentLRQ : function(graphic){
				   	if(!graphic){
				   		return;
				   	}

					//设置地图视图范围
				   	if(graphic.geometry.type == "point"){
				   		$gisObject.map.centerAt(graphic.geometry);
				   		return;
			       	}
			       	var rExtent = $itfreer_arcgis_core.getMaxExtent([graphic]);
			    	$gisObject.map.setExtent(rExtent);
			    },

			    /**
				 * 清除查询结果，并返回查询页面
				 */
			    clearSearchResult : function(searchName){
			    	$gisObject.searchParameter[searchName].searchPanel = true;
			    	$itfreer_arcgis_draw.deDrawAndClearGraphics();

			    	// 清除查询数据
			       	if($gisObject.searchParameter[searchName].resultLayerIds
			       		&& $gisObject.searchParameter[searchName].resultLayerIds.length>0){
			       		for(var i=0;i<$gisObject.searchParameter[searchName].resultLayerIds.length;i++){
			       			var tempLN = $gisObject.searchParameter[searchName].resultLayerIds[i];
			       			$gisObject.searchParameter[tempLN] = {};
			       		}
			       	}
			       	$gisObject.searchParameter[searchName].resultLayerIds = [];
			       	$gisObject.searchParameter[searchName].searchResultList = [];
					$gisObject.searchParameter[searchName].searchPageList = [];
			    },

			     /**
				 * 显示指定查询面板
				 */
			    showSearchTab : function(searchName, id){
			    	$itfreer_form_core.setTab(searchName, 'tab' + id);
			    	$itfreer_arcgis_search.showPageResults(searchName + '_' + id);
			    },

			    /**
				 * 是否可显示tab选项卡
				 */
			    canShowTab : function(searchName, id){
			    	return $itfreer_arcgis_search.hasLayer(searchName, id) && $formObject.tabs[searchName].tabShow['tab'+id];
			    },

			    showPopAndFeature : function(objectid, searchName){
			    	$itfreer_arcgis_search.selectPop(objectid, searchName);
			    	$itfreer_arcgis_search.selectFeature(objectid, searchName);
			    },

			    hidePopAndFeature : function(objectid, searchName){
			    	$itfreer_arcgis_search.unSelectPop(objectid, searchName);
			    	$itfreer_arcgis_search.unSelectFeature(objectid, searchName);
			    }
			};
			for(f in $itfreer_arcgis_search){
				$rootScope[f] = $itfreer_arcgis_search[f];
			}
			return $itfreer_arcgis_search;
		}
	);

	/* 
	 * 加载服务器
	 */
	itfreerArcgisSearchModule.run(function($rootScope, $itfreer_arcgis_search) {
	  	
	});
}(window, angular));
/**itfreer.core.js**/
/* itfreer v1.1
 * wdp web应用开发平台
 * 此类定义应用的基础代码
 */
;
/**
 * 初始化全局变量
 */
(function() {
	/**
	 * IE8兼容
	 */
	document.createElement('ng-include');
	document.createElement('ng-pluralize');
	document.createElement('ng-view');
	document.createElement('ng:include');
	document.createElement('ng:pluralize');
	document.createElement('ng:view');

	document.createElement('ag-Combotree');
	document.createElement('ag-Combobox');
	document.createElement('ag-Treegrid');
	document.createElement('ag-Datebox');
	document.createElement('ag-Textarea');
	document.createElement('ag-Upload');
	document.createElement('ag-Impexcel');
	document.createElement('ag-User');
	document.createElement('ag-Date');
	document.createElement('ag-Print-Button');
 
	/**
	 * 通用方法扩展，forEach方法
	 */
	if (!Array.prototype.forEach) {
		Array.prototype.forEach = function(callback, thisArg) {
			var T, k;
			if (this == null) {
				throw new TypeError(" this is null or not defined");
			}
			var O = Object(this);
			var len = O.length >>> 0;
			if ({}.toString.call(callback) != "[object Function]") {
				throw new TypeError(callback + " is not a function");
			}
			if (thisArg) {
				T = thisArg;
			}
			k = 0;
			while (k < len) {
				var kValue;
				if (k in O) {
					kValue = O[k];
					callback.call(T, kValue, k, O);
				}
				k++;
			}
		};
	}

	/**
	 * 通用方法扩展，删除数组中的索引项
	 */
	Array.prototype.remove = function(row){
		var dx = this.indexOf(row,0);
		if(isNaN(dx) || dx > this.length){
			return;
		}
		this.splice(dx,1);
	};

	/**
	 * 通用方法扩展，去掉字符的空间
	 */
	String.prototype.trim = function() {
	    return this.replace(/(^\s*)|(\s*$)/g,'');
	};

	/**
	 * 创建Color对象
	 */
	createColorFromHex = function(hexCode) {
	  	if(hexCode.length==4) {
	    	var shortHexCode = hexCode; 
	    	var hexCode = '#';
	    	for(var i=1;i<4;i++) { 
	        	hexCode += (shortHexCode.charAt(i) + 
				shortHexCode.charAt(i)); 
	    	}
	  	}
	   	if ( hexCode.indexOf('#') == 0 ) {
	       	hexCode = hexCode.substring(1);
	   	}
	   	var red   = hexCode.substring(0,2);
	   	var green = hexCode.substring(2,4);
	   	var blue  = hexCode.substring(4,6);
	   	var rgb = { r: parseInt(red,16), g : parseInt(green,16), b : parseInt(blue,16) };
	   	return rgb;
	};
}).call(this);

/**
 * 定义itfreer模块，做为核心模板，定义基础方法
 */
(function(window, angular, undefined){
	/**
	 * 定义核心模块
	 */
	var itfreerModule = angular.module('itfreer.core', ['ui.router']);

	/**
	 * 定义核心模块依赖注入器
	 */
	itfreerModule.factory('$itfreer_core', function($rootScope) {
		$itfreer_core = {
			/**
			 * 通用方法扩展，获取cookie方法
			 */
			getCookie : function(sName) { 
			    var aCookie = document.cookie.split(";");
			    var lastMatch = null;
			    for (var i = 0; i < aCookie.length; i++) {
			        var aCrumb = aCookie[i].split("=");
			        if (sName == aCrumb[0].trim()) {
			            lastMatch = aCrumb;
			        }
			    }
			    if (lastMatch) {
			        var v = lastMatch[1];
			        if (v === undefined) return v;
			        return unescape(v);
			    }
			    return null;
			},

			/**
			 * 对比两个对象是否相同
			 */
			objEquals : function(objA, obj){
				if(typeof(obj)=="undefined"||obj==null||typeof(obj)!="object") 
			        return false;
			    if(typeof(objA)=="undefined"||objA==null||typeof(objA)!="object") 
			        return false;
			    if(objA == obj) 
			        return true;
			    
			    if(typeof(obj)=="undefined"||obj==null||typeof(obj)!="object") 
			        return false;
			    var length = 0; var length1=0;
			    for(var ele1 in objA) {
			        length++;
			    }               
			    for(var ele2 in obj) {
			        length1++;
			    }               
			    if(length!=length1) 
			        return false;
			    if(obj.constructor==objA.constructor){
			        for(var ele in objA){
			            if(typeof(objA[ele])=="object") {
			                if(!objA[ele].equals(obj[ele]))
			                    return false;
			            }
			            else if(typeof(objA[ele])=="function"){
			                if(!objA[ele].toString().equals(obj[ele].toString())) 
			                    return false;
			            }
			            else if(objA[ele]!=obj[ele]) 
			                return false;
			        }
			        return true;
			    }
			    return false;
			},

			/**
			 * 获取对象
			 */
			getBinder : function(scope, attrs) {
				if(!attrs){
					return null;
				}
				try{
					var props = attrs.split('.');
					if (props.length == 1){
						return {obj : scope.$parent, field : props[0]};
					} else if (props.length == 2){
						return { obj : scope.$parent[props[0]], field : props[1]};
					} else if (props.length == 3){
						return { obj : scope.$parent[props[0]][props[1]], field : props[2]};
					} else if (props.length == 4){
						return { obj : scope.$parent[props[0]][props[1]][props[2]], field : props[3]};
					}
				}catch(e){
					return null;
				}
			},

			/**
			 * 获取是否为IE浏览器
			 */
			isIE : function() {  
			    if (!!window.ActiveXObject || "ActiveXObject" in window)  
			        return true;  
			    else  
			        return false;  
			},

			/**
			 * 获取日期对象
			 */
			getDateObject : function(input) {
				if (input == null) {
					return '';
				}
				try{
					var dType = typeof (input);
					var date = null;
					if (dType == 'date') {
						date = input;
					} else if (dType == 'object') {
						if (input.hasOwnProperty('time')) {
							date = new Date(input.time);
						} else {
							return input;
						}
					} else if (dType == 'string') {
						date = new Date(Date.parse(input));
					} else if(dType == "undefined"){
						return "";
					}

					if ($itfreer_core.isIE()){
					    var array = input.match(/\d+/g);  
				    	input = array[0]+'-'+array[1]+'-'+array[2];
				    	return input;
					}else{
						var y = date.getFullYear();
						var m = date.getMonth() + 1;
						var d = date.getDate();
						var result = "";
						result = y + '-' + m + '-' + d;
						return result;
					}
				}catch(e){
					return input;
				}
			},

			/**
			 * 日期格式化
			 */
			formatDate : function(date) {
				var month = date.getMonth() + 1;
				if ("" != date) {
					if (date.getMonth() + 1 < 10) {
						month = '0' + (date.getMonth() + 1);
					}
					var day = date.getDate();
					if (date.getDate() < 10) {
						day = '0' + date.getDate();
					}
					return date.getFullYear() + '-' + month + '-' + day;
				} else {
					return "";
				}
			},

			/**
			 * 获取url地址的参数
			 */
			getRequest : function() {
			  var url = location.search; //获取url中"?"符后的字串
			   var theRequest = new Object();
			   if (url.indexOf("?") != -1) {
			      var str = url.substr(1);
			      strs = str.split("&");
			      for(var i = 0; i < strs.length; i ++) {
			         theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
			      }
			   }
			   return theRequest;
			},

			/**
			 * 获取对象是否为null或未定义
			 */
			isNullOrUndefined : function(thing) {
				if(!thing){
					return true;
				}

				if(thing == null){
					return true;
				}

				if(typeof(thing) == undefined){
					return true;
				}

				return false;
		    },

		    /**
			 * 获取对象是否有对象
			 */
			isHasProperty : function(obj, field) {
				if(!isNullOrUndefined(obj)){
					return obj.hasOwnProperty(field);
				}else{
					return false;
				}
		    },

		    /**
			 * 获取对象是否有对象，并且不为空
			 */
			isHasPropertyAndNoNull : function(obj, field) {
				if(!isNullOrUndefined(obj)){
					if(obj.hasOwnProperty(field)){
						var value = obj[field];
						return !isNullOrUndefined(value);
					}else{
						return false;
					}
				}else{
					return false;
				}
		    },

		    /**
			 * 左部填充
			 */
		    leftPad : function(s, mL, seq) {
				return (Array(mL + 1).join(seq) + s).split('').reverse().join('').substring(0, mL).split('').reverse().join('');
			},

			/**
			 * 获取GUID值
			 */
		    getGUID : function(){
				var a = function(a){
					return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN
				};
				var b = function(a,b){
					for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e){
						d&1&&(c=e+c);
					}
					return c;
				};

				var myDate = new Date();
				//获取完整的年份(4位,1970-????)
				var year = myDate.getFullYear();
				//获取当前月份(0-11,0代表1月)
				var month = myDate.getMonth() + 1;
				//获取当前日(1-31)
				var day = myDate.getDate();
				//获取当前小时数(0-23)
				var hours = myDate.getHours();
				//获取当前分钟数(0-59)
				var minutes = myDate.getMinutes();
				//获取当前秒数(0-59)
				var seconds = myDate.getSeconds();

				var guidString = b(a(32),8)+b(a(16),4)+b(16384|a(12),4)+b(32768|a(14),4)+b(a(48),12);
				
				return (year.toString()
							+ this.leftPad(month.toString(),2,'0')
							+ this.leftPad(day.toString(),2,'0')
							+ this.leftPad(hours.toString(),2,'0')
							+ this.leftPad(minutes.toString(),2,'0')
							+ this.leftPad(seconds.toString(),2,'0')
							+ guidString);
			},

			/**
			 * 将对象转换为json字符串
			 */
			toJSONStr : function(obj) {
				if (typeof obj === 'string')
					return obj;
				if (typeof obj === 'object'){
					if(obj == null)
						return ;
					return JSON.stringify(obj);
				}
				throw new Error('参数必须为对象（数组）或对象（数组）的JSON字符串');
			},

			/**
			 * 验证是否为数字
			 */
			validateNum : function(num) {
				var reg = new RegExp("^[0-9]*$");
				if (!reg.test(num)) {
					return false;
				}
				return true;
			},

			/**
			 * 当前数是否为双数
			 */
			isDoubleNum : function(num){
				var i = num % 2;
				if(i==0){
					return true;
				}else{
					return false;
				}
			}
		};
		for(f in $itfreer_core){
			$rootScope[f] = $itfreer_core[f];
		}
		return $itfreer_core;
	});

	/**
	 * 处理显示长度
	 */
	itfreerModule.filter("asLength", function () {
	    return function (input, maxLength) {
	    	if(input==null || input==""){
	    		return "";
	    	}
	    	if(input.length<=maxLength){
	    		return input;
	    	}else{
	    		input = input.substring(0, maxLength-3) + "...";
	    		return input;
	    	}
	    };
	});

	/**
	 * 日期转换
	 */
	itfreerModule.filter("asDate", ['$itfreer_core', function ($itfreer_core) {
	    return function (input) {
	    	return $itfreer_core.getDateObject(input);
	    };
	}]);
	
	/**
	 * 日期转换
	 */
	itfreerModule.filter("sdeField", ['$itfreer_core', function ($itfreer_core) {
	    return function (input) {
	    	var infos = input.split(".");
	    	return infos[infos.length - 1];
	    };
	}]);
	
	/**
	 * 获取第一张图片路径
	 */
	itfreerModule.filter("firstImgUrl", ['$itfreer_core', function ($itfreer_core) {
	    return function (url) {
	    	if(!url) return "";
	    	if(url.indexOf("|") > 0)
			{
				 var arr = url.split("|");
				 return String(arr[arr.length-1].toString().split(":")[0]);
		    }
			 else{
				 var arr = url.split(":");
				return String(arr[0]);
			 }
	    };
	}]);
	
	/**
	 * 获取第一张图片名称
	 */
	itfreerModule.filter("firstImgName", ['$itfreer_core', function ($itfreer_core) {
	    return function (url) {
	    	if(!url) return "";
	    	if(url.indexOf("|") > 0)
			{
				 var arr = url.split("|");
				 return String(arr[arr.length-1].toString().split(":")[1]);
		    }else{
				 var arr = url.split(":");
				 return String(arr[1]);
			}
	    };
	}]);

	/* 
	 * 加载服务器
	 */
	itfreerModule.run(function($rootScope, $itfreer_core) {
	  	
	});
}(window, angular));
/**itfreer.form.builder.js**/
/**
 * 定义itfreer.form.builder模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义构建模块
	 */
	var itfreerformBuilderModule = angular.module('itfreer.form.builder', ['itfreer.form.core']);

	/**
	 * 定义表单变量
	 */
	itfreerformBuilderModule.value('$builderObject',{
		// 定义当前查询列表
		baseTables : [],
		// 包名称
		jarName : "com.hrt.ps.data",
		// 构建路径
		buildPath : "c:\\builder"
	});

	/**
	 * 定义表单数据访问服务
	 */
	itfreerformBuilderModule.factory('$itfreer_form_builder', 
			function($rootScope, $http, $builderObject, $itfreer_core, $itfreerHttp) {
		$itfreer_form_builder = {
			// 导入字段数据
			inputFields : function(formName, tableName, fieldTableName, keyField){
				formName = formName ? formName : 'fd';
				if(!$formObject[formName].editRow.hasOwnProperty('childValues')){
					$formObject[formName].editRow.childValues = {};
				}
				$itfreerHttp.getTableFields(fieldTableName,
					function(data){
						$rootScope.$apply(function() {
							$formObject[formName].editRow.childValues[tableName] = [];
							var list = [];
							data.forEach(function(e){  
								var obj = {};
								var guid = $itfreer_core.getGUID();
								obj[keyField] = guid;
								obj[$formObject.isNew]=true;
								obj.S_FIELDNAME=e.fieldName;
								obj.S_FIELDALIASNAME=e.fieldAliasName;
								obj.S_DATATYPE=e.dataType;
								obj.I_MAXLEN=e.maxLen;
								obj.I_DECIMALDIGITS=e.decimaldigits;
								obj.S_CONTROLTYPE=e.controlType;
								obj.S_UNIT=e.unit;
								list.push(obj);
								$formObject[formName].editRow.childValues[tableName].push(obj);
							});
							$formObject[formName].editRow.childValues[tableName] = list;
						});
					}, 
					function(ex){
					}
				);
			},
			
			// 构建表单
			builder : function(formID){
				$itfreerHttp.builder(formID, function(data){
					$.messager.alert('系统提示', '构建成功！');
				}, function(ex){
					$.messager.alert('系统提示', '构建失败！');
				});
			},
			
			// 构建数据表
			builderTables : function(){
				$itfreerHttp.builderTables($builderObject.jarName, $builderObject.buildPath, function(data){
					$.messager.alert('系统提示', '构建成功！');
				}, function(ex){
					$.messager.alert('系统提示', '构建失败！');
				});
			},
			
			// 构建数据表
			builderTable : function(id){
				$itfreerHttp.builderTable(id, $builderObject.jarName, $builderObject.buildPath, function(data){
					$.messager.alert('系统提示', '构建成功！');
				}, function(ex){
					$.messager.alert('系统提示', '构建失败！');
				});
			},
			
			// 构建表单
			initBaseTables : function(){
				$itfreerHttp.initBaseTables(function(data){
					$rootScope.$apply(function() {
						$builderObject.baseTables = data;
					});
				}, function(ex){
				});
			}
		};
		for(f in $itfreer_form_builder){
			$rootScope[f] = $itfreer_form_builder[f];
		}
		$rootScope.builderObject = $builderObject;
		return $itfreer_form_builder;
	}); 

	/* 
	 * 加载服务器
	 */
	itfreerformBuilderModule.run(function($rootScope, $itfreer_form_builder, $builderObject) {
	  	
	});
}(window, angular));
/**itfreer.form.core.js**/
/**
 * 定义表单itfreer.form.core模块
 * 包括tab选项，控件，权限等管理
 */
(function(window, angular, undefined){
	/* 
	 * 定义表单的核心模块
	 */
	var itfreerformcoreModule = angular.module('itfreer.form.core', ['itfreer.core']);

	/**
	 * 定义表单变量
	 */
	itfreerformcoreModule.value('$formObject',{
		/**
		 * tab选项卡管理
		 */
		tabs : {},
		/**
		 * 菜单选项卡管理
		 */
		menuClass : {},
		/**
		 * 默认表单
		 */
		df : {
			/**
			 * 表单的主表名称
			 */
			tableName : '',
			/**
			 * 表单的主健，只能为一个，一般为GUID字段
			 */
			keyField : '', 	
			/**
			 * 表单所绑定的工作流ID
			 */
			bmpKey 	: '',
			/**
			 * 表单需要随机赋值的字段
			 */
			randomFields : '',
			/**
			 * 表单默认值
			 */
			defaultObject : {},
			/**
			 * 主表的默认的查询值
			 */
			queryValue : {},
			 /**
			 * 主表的排序对象
			 */
			orderObject : {},
			/**
			 * 表单中treeGird控件名称
			 */	
			treeGirdName : '',
			/**
			 * 表单中treeGrid的idField
			 */	
			idField : '',
			/**
			 * 表单中treeGrid的PIDField
			 */	
			pIDField : '',
			/**
			 * 表单中treeGrid的默认加载级别
			 */
			treeLoadJBs : '',
			/**
			 * 表单中treeGrid的树级别字段
			 */
			treeJBField : '',
			/**
			 * 表单中treeGrid的树是否叶子节点字段
			 */
			treeIsChildField : '',
			/**
			 * 主表单的列表数据
			 */
			editList : {
				/**
				 * 数据列表
				 */
				list : null,
				/**
				 * 当前选择的行
				 */
				checkedRow : null,
				/**
				 * 当前选择的行集合
				 */
				checkedRows : null,
				/**
				 * 分页大小
				 */
				pageSize : 15,
				/**
				 * 分页索引
				 */
				pageIndex : 1,
				/**
				 * 页数
				 */
				pageCount : 0,
				/**
				 * 分页对象列表(1,2,3)
				 */
				pageList: [1],
				/**
				 * 总的条数
				 */
				rowsCount: 0
			}, 
			/**
			 * 主表单当前编辑对象
			 */
			editRow : null,
			/**
			 * 主表单当前编辑对象的复制对象，用于解决编辑中的结果处理
			 */
			curOldRow : null,
			/**
			 * 一级子表的当前编辑记录
			 */
			cEditRow : null,
			/**
			 * 一级子表的当前编辑记录的复制对象
			 */	
			cOldRow : null,
			/**
			 * 主表的查询变量
			 */
			queryObject : null,
			/**
			 * 主表的查询变量的复制对象
			 */
			oldQueryObject : null,
			/**
			 * 主表的定义当前工作流的表单配置信息
			 */
			bpmFormList : null,
			/**
			 * 主表的当前工作流当前任务的表单配置信息
			 */
			bpm : null,
			/* 
			 * 是事为MIS视图
			 */
			isMIS : true
		},

		/**
		 * 当前注册的表单名称，单页
		 */
		formNames : [],

		/**
		 * easy ui window窗口的收集器，用于对象删除
		 */
		windows : [],

		/**
		 * easy ui combotree
		 */
		combotrees : [],

		/**
		 * easy ui combobox
		 */
		comboboxs : [],

		/**
		 * easy ui treegrid
		 */
		treegrids : [],

		/**
		 * easy ui Datebox
		 */
		dateboxs : [],
		/**
		 * easy ui datetimeboxs
		 */
		datetimeboxs : [],
		/**
		 * 审批历史记录
		 */
		historyRow : [],
		/**
		 * 定义工作流下一节点的审批人信息
		 */
		nextAssignees : [],
		/**
		 * 定义汇签情况下，提交那个任务节点
		 */
		nextTasks : [],
		/**
		 * 流程交办的用户编号与名称
		 */
		bpmJb : {},

		/**
		 * 处理权限安全控制
		 */
		si : {},
		/**
		 * 用户
		 */
		user : {},

		/**
		 * 对象是否为新对象判断值
		 */
		isNew : "FIELD_ISNEW",
		 /**
		 * 新增的对象选择字段属性
		 */
		selectedField : "selected",
		/**
		 * 密码修改对象
		 */
		password : {},

		/**
		 * 是否异步操作中(如：保存，删除，取子表等)
		 */
		isOptioning : false
	});

	/**
	 * 定义核心模块服务，定义数据查询方法
	 */
	itfreerformcoreModule.factory('$itfreerHttp', function($rootScope, $state, 
		$formObject, $itfreer_core) {
		var sessionId = $("#_sessionid").html();
		var $itfreerHttp = {
			/**
			 * 保存单个对象，row为js对象
			 */
			save : function(tableName, row, onsucess, onerror) {
				var args = { data : row };
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/save.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : function(data,textStatus,jqXHR){
						if(onsucess){
							onsucess(data);
						}
					},
					error: function(jqXHR,textStatus,errorThrown){
						if(onerror){
							onerror(jqXHR,textStatus,errorThrown);
						}else{
							$.messager.alert("错误",jqXHR.responseText,"error");
						}
					}
				});
			},

			/**
			 * 保存多个对象，rows为js数组对象
			 */
			saveList : function(tableName, rows, callback, onerror) {
				var args = {
					data : rows
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/saveList.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 删除数据，根据数据行，row为数据行条件，json对象
			 */
			deleteByKeyInBpm : function(tableName, row, activitiKey, callback, onerror) {
				var args = {
					data : row,
					akey : activitiKey
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/deleteByKeyInBpm.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 删除数据，根据数据行，row为数据行条件，json对象
			 */
			deleteByKey : function(tableName, row, callback, onerror) {
				var args = {
					data : row
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/deleteByKey.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取对象根据主键
			 */
			getEntityByKey : function(tableName, key, callback, onerror) {
				var args = {
					data : key
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getEntityByKey.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取数据行根据分页条件，query：查询条件，Map对象，Json格式；order：排序条件，Map对象，Json格式
			 */
			getPageRows : function(tableName, query, order, pageSize, pageIndex, callback, onerror) {
				var args = {
					queryData : query,
					orderData : order,
					pageSizeData : pageSize,
					pageIndexData : pageIndex,
					sessionId:sessionId
				};
				args.queryData = $itfreer_core.toJSONStr(args.queryData);
				args.orderData = $itfreer_core.toJSONStr(args.orderData);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getPageRows.do',
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取数据行根据分页条件，query：查询条件，Map对象，Json格式；order：排序条件，Map对象，Json格式
			 */
			getTreeData : function(tableName, query, order, pId, jbs, domainname, pageSize, pageIndex, useCache, callback, onerror) {
				var args = {
					queryData : query,
					orderData : order,
					pID : pId,
					JBs : jbs,
					domainName:domainname,
					pageSizeData : pageSize,
					pageIndexData : pageIndex
				};
				args.queryData = $itfreer_core.toJSONStr(args.queryData);
				args.orderData = $itfreer_core.toJSONStr(args.orderData);
				
				var typeString = "POST";
				if(useCache){
					typeString = "GET";
				}
				
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getTreeData.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取字典值 ，使用GET方法，并使用缓存
			 */
			getDomains : function(tableName, domainName, filter, addPinYin, callback, onerror) {
				filter = filter ? $itfreer_core.toJSONStr(filter) : '';
				var args = {
					data : domainName,
					filterObject : filter,
					addPinYin : addPinYin
				};
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getDomains.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			}, 

			/**
			 * 获取字典值
			 */
			getDomainsEx : function(tableName, domainName, cStatic, callback, onerror) {
				var args = {
					data : domainName,
					convertStatic : cStatic
				};
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getDomainsEx.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取子表数据
			 */
			getChildData : function(tableName, row, childTablesString, callback, onerror) {
				var args = {
					data : row,
					childTables : childTablesString
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getChildData.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取子表数据
			 */
			getChildDataEx : function(tableName, row, childTablesString, childOrdersString, callback, onerror) {
				var args = {
					data : row,
					childTables : childTablesString,
					childOrders : childOrdersString
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getChildDataEx.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取子表数据
			 */
			getChildDataEx2 : function(tableName, row, childTablesString, childOrdersString, tagetTableNames, callback, onerror) {
				var args = {
					data : row,
					childTables : childTablesString,
					childOrders : childOrdersString,
					tagetTableNames : tagetTableNames
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getChildDataEx2.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 导出doc
			 */
			exportDoc : function(dataMap, flt, fileName, callback, onerror){
				var args = { dataMap : dataMap, flt : flt, fileName : fileName };
				args.dataMap = $itfreer_core.toJSONStr(args.dataMap);
				$.ajax({
					url : getBasePath()+'/word/export.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'text',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 导出Excel
			 */
			exportExcel : function(tableName,exportInfo,moduleName,fileName,template,queryFields,displayFields,whereString,orderByString,selectFields,groupByString,whereParameter,isNullHeJi,callback,onerror){
				var args = {
					tableName : tableName,
					exportInfo : $itfreer_core.toJSONStr(exportInfo),
					moduleName : moduleName,
					fileName : fileName,
					template : template,
					queryFields : queryFields,
					displayFields : displayFields,
					whereString : $itfreer_core.toJSONStr(whereString),
					orderByString : $itfreer_core.toJSONStr(orderByString),
					selectFields : $itfreer_core.toJSONStr(selectFields),
					groupByString : $itfreer_core.toJSONStr(groupByString),
					whereParameter : $itfreer_core.toJSONStr(whereParameter),
					isNullHeJi : isNullHeJi
				}
				$.ajax({
					url : getBasePath()+'/excel/export.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'text',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 清除角色缓存
			 */
			clearRoleCache : function(callback, onerror) {
				var args = {};
				$.ajax({
					url : getBasePath()+'/role/clearcache.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 清除工作日设置缓存
			 */
			clearWorkDayCache : function(callback, onerror) {
				var args = {};
				$.ajax({
					url : getBasePath()+'/workDay/clearWorkDayCache.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 停止使用角色委托
			 */
			enableRoleWt : function(key, callback, onerror) {
				var args = { rowKey : key };
				args.rowKey = $itfreer_core.toJSONStr(args.rowKey);
				$.ajax({
					url : getBasePath()+'/role/enable.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 重新加载委托
			 */
			reloadWt : function(key, callback, onerror) {
				var args = { rowKey : key };
				args.rowKey = $itfreer_core.toJSONStr(args.rowKey);
				$.ajax({
					url : getBasePath()+'/role/reloadWt.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 保存密码
			 */
			savePassword : function(oldPW, newPW, rnewPW, callback, onerror) {
				var args = {
						oldPW : oldPW,
						newPW : newPW,
						rnewPW : rnewPW
				};
				$.ajax({
					url : getBasePath()+'/safe/password.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 设置地图的默认配置
			 */
			setDefulatConfig : function(callback, onerror){
				$.ajax({
					url : getBasePath()+'/gis/defulatconfig.do?sessionId='+sessionId,
					type: 'POST',
					data: null,
					timeout : 50000,
					dataType: 'text',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 获取表字段数据
			 */
			getTableFields : function(tablename, callback, onerror) {
				var args = {
					tableName : tablename
				};
				$.ajax({
					url : getBasePath()+'/builder/getTableFields.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 构建表单
			 */
			builder : function(formID, callback, onerror){
				var args = { formid : formID };
				$.ajax({
					url : getBasePath()+'/builder/builder.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'json',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 构建所有数据表
			 */
			builderTables : function(jarName, ptah, callback, onerror){
				var args = { JarName : jarName, ptah : ptah };
				$.ajax({
					url : getBasePath()+'/builder/builderTables.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'json',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 构建数据表
			 */
			builderTable : function(id, JarName, ptah, callback, onerror){
				var args = { table : id, JarName : JarName, ptah : ptah };
				$.ajax({
					url : getBasePath()+'/builder/builderTable.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'json',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 加载所有数据表
			 */
			initBaseTables : function(callback, onerror){
				$.ajax({
					url : getBasePath()+'/builder/getBaseTables.do?sessionId='+sessionId,
					type: 'POST',
					timeout : 35000,
					dataType: 'json',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 流程图
			 */
			getBpmImage : function(exeId, callback, onerror) {
				var args = { executionId : exeId };
				args.executionId = $itfreer_core.toJSONStr(args.executionId);
				$.ajax({
					url : getBasePath()+'/workflow/exeimage.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'text',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获审批历史
			 */
			getBpmHistory : function(exeId, callback, onerror) {
				var args = { executionId : exeId };
				args.executionId = $itfreer_core.toJSONStr(args.executionId);
				$.ajax({
					url : getBasePath()+'/workflow/history.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取表单配置
			 */
			getBpmForm : function(dId, tId, callback, onerror) {
				var args = { definitionId : dId, taskId : tId };
				args.definitionId = $itfreer_core.toJSONStr(args.definitionId);
				args.taskId = $itfreer_core.toJSONStr(args.taskId);
				$.ajax({
					url : getBasePath()+'/workflow/form.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取所有表单配置
			 */
			getBpmForms : function(dId, callback, onerror) {
				var args = { definitionId : dId };
				args.definitionId = $itfreer_core.toJSONStr(args.definitionId);
				$.ajax({
					url : getBasePath()+'/workflow/forms.do?sessionId='+sessionId,
					type : 'GET',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取所有表单配置
			 */
			getWorkList : function(query, order, pageSize, pageIndex, getAllCount, refresRowCount, callback, onerror) {
				var args = {
					queryData : query,
					orderData : order,
					pageSizeData : pageSize,
					pageIndexData : pageIndex,
					getAllCount : getAllCount,
					refresRowCount : refresRowCount
				};
				args.queryData = $itfreer_core.toJSONStr(args.queryData);
				args.orderData = $itfreer_core.toJSONStr(args.orderData);
				$.ajax({
					url : getBasePath()+'/workflow/worklist.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},
			
			/**
			 * 自动构建流程配置
			 */
			autoSaveTask : function(pdId, callback, onerror) {
				var args = {
						processDefinitionId : pdId
				};
				$.ajax({
					url : getBasePath()+'/workflow/autoSaveTask.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 挂起或者激活流程定义
			 */
			suspendOrActivateByBpm : function(pdId, type, callback, onerror) {
				var args = {
					processDefinitionId : pdId,
					type : type
				};
				$.ajax({
					url : getBasePath()+'/workflow/suspendOrActivateDef.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 挂起或者激活流程实例
			 */
			suspendOrActivateByInst : function(instId, type, businessId, callback, onerror) {
				var args = {
					processInstanceId : instId,
					type : type,
					businessId : businessId
				};
				$.ajax({
					url : getBasePath()+'/workflow/suspendOrActivateInst.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 设置地图的默认配置
			 */
			setDefulatConfig : function(callback, onerror){
				$.ajax({
					url : getBasePath()+'/gis/defulatconfig.do?sessionId='+sessionId,
					type: 'POST',
					data: null,
					timeout : 50000,
					dataType: 'text',
					success: callback,
					error: onerror
				});
			}
		};
		return $itfreerHttp;
	});

	/**
	 * 定义核心模块服务
	 */
	itfreerformcoreModule.factory('$itfreer_form_core', 
		function($rootScope, $state, $formObject, $itfreerHttp, $itfreer_core) {
		var sessionId = $("#_sessionid").html();
		var $itfreer_form_core = {

			// //打印插件地址
			urls : {
				lodopPlugin64 : "../style/script/lodop/iinstall_lodop6.194.64.exe",
				lodopPlugin32 : "../style/script/lodop/install_lodop6.194.32.exe"
			},

			/**
			 * 获取lodop打印对象
			 */
			getLodop : function () {
				//lodop打印
				var lodop = navigator.appVersion.indexOf("MSIE") >= 0 ? 
					document.getElementById('LODOP_OB') :
					document.getElementById('LODOP_EM');
				if(!lodop || !lodop.VERSION || lodop.VERSION < "6.1.4.5")
					return null;
				return lodop;
			},
			
			/**
			 * 设置默认的VIEW名称
			 */
			setDefulatUiView : function(viewName){
				var  topMenu = $("li[top_menu][ui-sref]");
				for(var i=0;i<topMenu.length;i++){
					var uiSelf = topMenu.attr("ui-sref");
					if(uiSelf){
						$state.go(uiSelf);
					}
					return;
				}
				$state.go(viewName);
			},

			/**
			 * 初始化tabs
			 */
			iniTab : function(tabName, tabItemNames, className){
				className = className ? className : 'selected';
				$formObject.tabs[tabName] = {};
				$formObject.tabs[tabName].className = className;
				$formObject.tabs[tabName].tabShow = {};
				$formObject.tabs[tabName].tabClass = {};
				
				var tNames = tabItemNames.split(",");
				tNames.forEach(function(item){
					$formObject.tabs[tabName].tabShow[item] = true;
					$formObject.tabs[tabName].tabClass[item] = className;
				});
			},

			/**
			 * 设置tabs的显示
			 */
			setTab : function(tabName, itemName){
				var items = itemName.split(',');
				if(!$formObject.tabs[tabName]){
					if(items.length>=1){
						$forestar_form_core.iniTab(tabName, items[0]);
					}else{
						$forestar_form_core.iniTab(tabName, items);
					}
				}
				if(items.length>1){
					items.forEach(function(e){
						$formObject.tabs[tabName].tabShow[e] = !$formObject.tabs[tabName].tabShow[e];
						if($formObject.tabs[tabName].tabShow[e]){
							$formObject.tabs[tabName].tabClass[e] = $formObject.tabs[tabName].className;
						}else{
							$formObject.tabs[tabName].tabClass[e] = "";
						}
					});
				}else{
					for(attribute in $formObject.tabs[tabName].tabShow){
						$formObject.tabs[tabName].tabShow[attribute] = false;
						$formObject.tabs[tabName].tabClass[attribute] = "";
					}
					$formObject.tabs[tabName].tabShow[itemName] = true;
					$formObject.tabs[tabName].tabClass[itemName] = $formObject.tabs[tabName].className;
				}
			},
			
			/**
			 * 初始化menuClass
			 */
			initMenuClass : function(classname){
				classname = classname ? classname : 'selected';
				//设置或获取对象指定的文件名或路径。
				var menu = window.location.pathname;
				$formObject.menuClass[menu] = classname;
			},

			/**
			 * 初始化当前用户和权限信息
			 */
			initSecurity:function(){
				var tags = $itfreer_core.getCookie("security_tag");
				$formObject.user.userid = $itfreer_core.getCookie("userid");
				$formObject.user.userrealname = decodeURI(escape($itfreer_core.getCookie("username")));
				$formObject.user.userdw = decodeURI(escape($itfreer_core.getCookie("userdw")));
				$formObject.user.dept = decodeURI(escape($itfreer_core.getCookie("deptname")));
				$formObject.user.userorg = decodeURI(escape($itfreer_core.getCookie("userorg")));
				$formObject.user.orgbh = decodeURI(escape($itfreer_core.getCookie("orgbh")));

				if(tags!=null){
					var tagList = tags.split(",");
					tagList.forEach(function(item){
						if(item.substring(0,1)=='"'){
							var sItem = item.substring(1,item.length);
							$formObject.si[sItem]=true;
						}else if(item.substr(item.length-1,1)=='"'){
							var sItem = item.substr(0,item.length-1);
							$formObject.si[sItem]=true;
						}else{
							$formObject.si[item]=true;
						}
					});
				}
			},

			/**
			 * 初始化table下表单属性
			 * 
			 * formName			表单名称
			 * tableName 		表单的主表名称
			 * keyField 		表单的主健，只能为一个，一般为GUID字段
			 * randomFields		表单需要随机赋值的字段
			 * orderObject 		主表的排序对象
			 * formValue		表单默认值
			 * queryValue 		主表的默认的查询值
			 * bmpKey 			表单所绑定的工作流ID
			 * pageSize			分页加载的分页数
			 * childTables
			 * childGridPara
			 * tagetTableNames
			 * childOrders
			 */
			initTablePara : function(formName, tableName, keyField, randomFields, 
					orderObject, formValue, queryValue, bpmKey, pageSize,
					childTables, childGridPara, tagetTableNames, childOrders){
				formName = formName ? formName : 'fd';
				$formObject.formNames.push(formName);
				$formObject[formName] = {};
				$formObject[formName].tableName = tableName;
				$formObject[formName].keyField = keyField;
				//随机赋值字段
				if (randomFields && randomFields!="") {
					$formObject[formName].randomFields = randomFields.split(',');
				}else{
					$formObject[formName].randomFields = [];
				}
				$formObject[formName].orderObject = orderObject;
				$formObject[formName].defaultObject = formValue;
				$formObject[formName].queryValue = queryValue;
				$formObject[formName].bmpKey = bpmKey;
				$formObject[formName].editList = {};
				$formObject[formName].editList.pageSize = pageSize ? pageSize : 20;
				$formObject[formName].editList.pageIndex = 1;
				$formObject[formName].editList.pageList = [];
				$formObject[formName].editList.pageList.push(1);
				$formObject[formName].queryObject = {};
				
				$formObject[formName].childTables = childTables;
				$formObject[formName].childGridPara = childGridPara;
				$formObject[formName].tagetTableNames = tagetTableNames;
				$formObject[formName].childOrders = childOrders;
			},

			// 初始化treeGrid下表单属性
			// formName			表单名称
			// tableName 		表单的主表名称
			// keyField 		表单的主健，只能为一个，一般为GUID字段
			// randomFields		表单需要随机赋值的字段
			// orderObject 		主表的排序对象
			// formValue		表单默认值
			// queryValue 		主表的默认的查询值
			// bmpKey 			表单所绑定的工作流ID
			// treeGirdName		树Grid的名称
			// idField			ID字段
			// pIDField			PID这段
			// treeJBField		树级别字段
			// treeIsChildField	树是否叶子节点字段
			// treeLoadJBs		树级别字段
			initTreePara : function(formName, tableName, keyField, randomFields, 
					orderObject, formValue, queryValue, bpmKey, 
					treeGirdName, idField, pIDField, treeJBField, 
					treeIsChildField, treeLoadJBs,
					childTables, childGridPara, tagetTableNames, childOrders){

				formName = formName ? formName : 'fd';
				$itfreer_form_core.initTablePara(formName, tableName, keyField, randomFields, 
						orderObject, formValue, queryValue, bpmKey, null, 
						childTables, childGridPara, tagetTableNames, childOrders);
				$formObject[formName].idField = idField;
				$formObject[formName].pIDField = pIDField;
				// 树级别字段
				$formObject[formName].treeJBField = treeJBField;
				// 树是否叶子节点字段
				$formObject[formName].treeIsChildField = treeIsChildField;
				$formObject[formName].treeGirdName = treeGirdName;
				$formObject[formName].treeLoadJBs = treeLoadJBs;
			},

			// 初始化表单属性并加载数据
			initAndLoadData : function(formName, tableName, keyField, randomFields, 
					orderObject, formValue, queryValue, bpmKey, pageSize, addResult,
					childTables, childGridPara, tagetTableNames, childOrders, loadScureess){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.initTablePara(formName, tableName, keyField, randomFields, 
						orderObject, formValue, queryValue, bpmKey, pageSize,
						childTables, childGridPara, tagetTableNames, childOrders);
				$itfreer_form_core.loadData(formName, true, addResult, loadScureess);
				if(bpmKey){
					$itfreer_form_core.loadBpmFormConfig(formName);
				}
			},

			// 数据分页加载 formName:表单名称，getRowCount:分页时是否计算所有数据记录数, addResult:是否添加查询结果到当前的结果集中，默认为false
			loadData : function(formName, getRowCount, addResult, loadScureess){
				formName = formName ? formName : 'fd';
				if(!$formObject[formName] || !$formObject[formName].tableName){
					return;
				}
				addResult = addResult ? addResult : false;
				getRowCount = getRowCount ? getRowCount : true;
				if(addResult){
					if(!objEquals($formObject[formName].oldQueryObject, $formObject[formName].queryObject)){
						$formObject[formName].oldQueryObject = jQuery.extend(true, {}, $formObject[formName].queryObject);
						addResult = false;
					}
				}
				$formObject[formName].editList.pageIndex = $formObject[formName].editList.pageIndex ? $formObject[formName].editList.pageIndex : 1;
				$itfreer_form_core.innerLoadData(formName, getRowCount, addResult, loadScureess);
			},
			
			// 数据分页加载 formName:表单名称，getRowCount:分页时是否计算所有数据记录数, addResult:是否添加查询结果到当前的结果集中，默认为false，loadScureess：加载成功
			// 目前还有分页加载数据时总计算数据总数的问题
			innerLoadData : function(formName, getRowCount, addResult, loadScureess){
				formName = formName ? formName : 'fd';
				addResult = addResult ? addResult : false;
				getRowCount = getRowCount ? getRowCount : true;
				
				var queryObject = jQuery.extend(true, $formObject[formName].queryObject, $formObject[formName].queryValue);
				var rowCount = $formObject[formName].editList.rowsCount ? $formObject[formName].editList.rowsCount : 0;
				
				$itfreerHttp.getPageRows($formObject[formName].tableName, queryObject , $formObject[formName].orderObject,
						$formObject[formName].editList.pageSize, $formObject[formName].editList.pageIndex,
					function(data){
						$rootScope.$apply(function() {
							if(!data){
								data = {};
								data.data = [];
								data.pageInfo = {};
								data.pageInfo.pageCount = 1;
								data.pageInfo.rowCount = 0;
							}
							
							$formObject[formName].editList.checkedRow=null;
							$formObject[formName].editList.checkedRows=[];
							
							$formObject[formName].editList.pageCount = data["pageInfo"]["pageCount"];
							$formObject[formName].editList.pageList = [];
							if($formObject[formName].editList.pageCount!=null && $formObject[formName].editList.pageCount!=99999999){
								for(var i=1;i<=$formObject[formName].editList.pageCount;i++){
									$formObject[formName].editList.pageList.push(i);
								}
							}else{
								$formObject[formName].editList.pageList.push(1);
							}

							$formObject[formName].editList.rowsCount = data["pageInfo"]["rowCount"];
							var dataList = data["data"] == null ? [] : data["data"];
							if(addResult){
								dataList.forEach(function(e){
									$formObject[formName].editList.list.push(e);
								});
							}else{
								$formObject[formName].editList.list = dataList;
							}

							if(loadScureess){
								loadScureess(formName, $formObject[formName].editList.list);
							}
						});
					}, 
					function(xhr){
					}
				);
			},
			
			// 设置查询条件并查询
			setQueryObjectAndQuery : function(formName, field, value){
				formName = formName ? formName : 'fd';
				if(value==null || value == "null"){
					if($formObject[formName].queryObject.hasOwnProperty(field)){
						delete $formObject[formName].queryObject[field];
					}
				}else{
					$formObject[formName].queryObject[field]=value;
				}
				$itfreer_form_core.loadData(formName, true, false);
			},
			
			// 设置排序对象
			setOrderObjectAndQuery : function(formName, field, value){
				formName = formName ? formName : 'fd';
				if(value==null || value == "null"){
					if($formObject[formName].orderObject.hasOwnProperty(field)){
						delete $formObject[formName].orderObject[field];
					}
				}else{
					$formObject[formName].orderObject[field]=value;
				}
				$itfreer_form_core.loadData(formName, true, false);
			},
			
			// 设置分页索引并且重新查询数据
			setPageIndexAndQuery : function(formName, pageIndex, addResult){
				formName = formName ? formName : 'fd';
				$formObject[formName].editList.pageIndex = pageIndex;
				$itfreer_form_core.loadData(formName, false, addResult);
			},
			
			//上一页
			prePage : function(formName, addResult){
				formName = formName ? formName : 'fd';
				var pageIndex = $formObject[formName].editList.pageIndex;
				pageIndex--;
				if(pageIndex<=0){
					pageIndex =1 ;
				}
				$itfreer_form_core.setPageIndexAndQuery(formName, pageIndex, addResult);
			},
			
			//下一页
			nextPage : function(formName, addResult){
				formName = formName ? formName : 'fd';
				var pageIndex = $formObject[formName].editList.pageIndex;
				var pageCount = $formObject[formName].editList.pageCount;
				pageIndex++;
				if(pageIndex>pageCount){
					pageIndex = pageCount ;
				}
				$itfreer_form_core.setPageIndexAndQuery(formName, pageIndex, addResult);
			},
			
			//首页
			firstPage : function(formName, addResult){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.setPageIndexAndQuery(formName, 1, addResult);
			},
			
			//尾页
			lastPage : function(formName, addResult){
				formName = formName ? formName : 'fd';
				var pageCount = $formObject[formName].editList.pageCount;
				$itfreer_form_core.setPageIndexAndQuery(formName, pageCount, addResult);
			},

			// 设置当前编辑记录 
			setEditRow : function(formName, row, childTables, childGridPara, tagetTableNames, childOrders){
				formName = formName ? formName : 'fd';
				if($formObject[formName].hasOwnProperty("childTables")){
					childTables = childTables ? childTables : $formObject[formName].childTables;
				}
				if($formObject[formName].hasOwnProperty("childGridPara")){
					childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				}
				if($formObject[formName].hasOwnProperty("tagetTableNames")){
					tagetTableNames = tagetTableNames ? tagetTableNames : $formObject[formName].tagetTableNames;
				}
				if($formObject[formName].hasOwnProperty("childOrders")){
					childOrders = childOrders ? childOrders : $formObject[formName].childOrders;
				}
				
				if(childGridPara){
					$itfreer_form_core.clearChildGridSelect(childGridPara);
				}
				
				if(row != null && !row[$formObject.isNew]){
					$formObject[formName].curOldRow = row;
					var copyRow = jQuery.extend(true, {}, row);
					
					// 处理直接子表
					if(childTables){
						$itfreer_form_core.loadRowChildValue(formName, copyRow, childTables, childOrders);
					}
					
					// 处理中间表第一种情况
					if(childTables && tagetTableNames){
						$itfreer_form_core.loadRowChildValueByTagetTable(formName, copyRow, childTables, childOrders, tagetTableNames);
					}
					
					// 处理中间表第二种情况
					if(childGridPara){
						$itfreer_form_core.loadRowChildValueByGrid(formName, copyRow, childGridPara);
					}
					
					$formObject[formName].editRow = copyRow;
				}else{
					if($formObject[formName].hasOwnProperty("defaultObject")){
						if(row!=null){
							row = jQuery.extend(true, row, $formObject[formName].defaultObject);
						}else{
							row = jQuery.extend(true, {}, $formObject[formName].defaultObject);
						}
					}else{
						if(row==null){
							row = {};
						}
					}
					row[$formObject.isNew]=true;
					$formObject[formName].editRow = row;
				}
				
				// 有工作流，处理流程配置信息
				if($formObject[formName].bmpKey){
					$itfreer_form_core.loadBpmTaskFormConfig(formName, row);
					$itfreer_form_core.setBpmTaskConfig(formName, row);
				}
			},
			
			// 为当前记录加载子表数据 row : 数据行， childTables : 子表名称 , 如 "table1,table2" , 
			//	childOrders 子表排序，如：I_ORDER:1:ORDERFIELD2:0,I_ORDER:0，用，分开顺序和子表的顺序一样
			loadRowChildValue : function(formName, row, childTables, childOrders){
				formName = formName ? formName : 'fd';
				childTables = childTables ? childTables : $formObject[formName].childTables;
				childOrders = childOrders ? childOrders : $formObject[formName].childOrders;
				
				if(row==null || childTables==null){
					return;
				}
				
				if(row.hasOwnProperty('childValues')){
					var childs = childTables.split(',');
					var needLoad = false;
					for(var i=0;i<childs.length;i++){
						if(!row.childValues.hasOwnProperty(childs[i])){
							needLoad = true;
							break;
						}
					}
					if(!needLoad){
						return;
					}
				}
				
				$itfreerHttp.getChildDataEx($formObject[formName].tableName, row, childTables, childOrders,
					function(data){
						$rootScope.$apply(function() {
							row.childValues = row.childValues ? row.childValues : {};
							if(data){
								data.forEach(function(e){
									for(attribute in e){ 
										row.childValues[attribute]=e[attribute];
									} 
								});
							}
							jQuery.extend(true, $formObject[formName].curOldRow, row);
						});
					}, 
					function(ex){
					}
				);
			},
			
			// 填充中间表子表数据，并根据中间表与关联的另外一张主表将外键关系，将另外一张主表的信息一起填充给中间子表记录
			// 如，用户表，用户角色表，角色表。当获取用户角色表时，可将角色表的信息一起查询出来，并给中间表子间填充
			// 如果另外一张主表中的字段在中间表中存在，则另外一张主表的字段改为字段名+"_OO"
			// row : 数据行， 
			// childTables : 中间表子表名称 , 如 "table1,table2" , 
			// childOrders : 子表排序，如：I_ORDER:1:ORDERFIELD2:0,I_ORDER:0，用，分开顺序和子表的顺序一样
			// tagetTableNames : 中间表关联表对象，如：tagetTableName:childField:tagetField:childField1:tagetField1,tagetTableName:childField:tagetField:childField1:tagetField1
			loadRowChildValueByTagetTable : function(formName, row, childTables, childOrders, tagetTableNames){
				formName = formName ? formName : 'fd';
				childTables = childTables ? childTables : $formObject[formName].childTables;
				childOrders = childOrders ? childOrders : $formObject[formName].childOrders;
				tagetTableNames = tagetTableNames ? tagetTableNames : $formObject[formName].tagetTableNames;
				
				if(row==null || childTables==null){
					return;
				}
				
				if(row.hasOwnProperty('childValues')){
					var childs = childTables.split(',');
					var needLoad = false;
					for(var i=0;i<childs.length;i++){
						if(!row.childValues.hasOwnProperty(childs[i])){
							needLoad = true;
							break;
						}
					}
					if(!needLoad){
						return;
					}
				}
				
				$itfreerHttp.getChildDataEx2($formObject[formName].tableName, row, 
						childTables, childOrders, tagetTableNames, 
					function(data){
						$rootScope.$apply(function() {
							row.childValues = row.childValues ? row.childValues : {};
							if(data){
								data.forEach(function(e){
									for(attribute in e){ 
										row.childValues[attribute]=e[attribute];
									} 
								});
							}
							jQuery.extend(true, $formObject[formName].curOldRow, row);
						});
					}, 
					function(ex){
					}
				);
			},
			
			// 加载中间表数据，并根据子表数据，实现对子表TreeGrid控件的选择(如：在用户中处理用户选择角色的情况)
			// row : 数据行， childTables : 子表名称 , 如'gridName,childTableName,gridKey,tableKey:gridName,childTableName,gridKey,tableKey'
			loadRowChildValueByGrid : function(formName, row, childGridPara){
				formName = formName ? formName : 'fd';
				childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				
				var childTables = "";
				// 更新子表数据
				if(childGridPara!=null){
					var childs = childGridPara.split(":");
					childs.forEach(function(item){
				     	var childItem = item.split(",");
				     	if(childItem.length==4){
				     		var childTableName = childItem[1];
				     		childTables += childTableName + ",";
				     	}
				    });
					childTables = childTables.substring(0, childTables.length-1);
				}
				$itfreer_form_core.clearChildGridSelect(childGridPara);
				
				if(row==null || childTables==null){
					$itfreer_form_core.updateChildGridSelect(childGridPara, row);
					return;
				}
				if(row.hasOwnProperty('childValues')){
					var childs = childTables.split(',');
					var needLoad = false;
					for(var i=0;i<childs.length;i++){
						if(!row.childValues.hasOwnProperty(childs[i])){
							needLoad = true;
							break;
						}
					}
					if(!needLoad){
						$itfreer_form_core.updateChildGridSelect(childGridPara, row);
						return;
					}
				}
				
				$itfreerHttp.getChildData($formObject[formName].tableName, row, childTables,
					function(data){
						$rootScope.$apply(function() {
							row.childValues = row.childValues ? row.childValues : {};
							if(data){
								data.forEach(function(e){
									for(attribute in e){ 
										row.childValues[attribute]=e[attribute];
									} 
								});
							}
							$itfreer_form_core.updateChildGridSelect(childGridPara, row);
							jQuery.extend(true, $formObject[formName].curOldRow, row);
						});
					}, 
					function(ex){
					}
				);
			},
			
			// 更新子Grid控件子表的选择
			updateChildGridSelect : function(childGridPara, row){
				childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				
				// 更新子表数据
				if(childGridPara!=null){
					var childs = childGridPara.split(":");
					childs.forEach(function(item){
				     	var childItem = item.split(",");
				     	if(childItem.length==4){
				     		var gridName = childItem[0];
				     		var childTableName = childItem[1];
				     		var gridKey = childItem[2];
				     		var tableKey = childItem[3];
				     		
				     		var tableData = row.childValues[childTableName];
				     		$itfreer_form_core.setChildSelect(gridName, tableData, gridKey, tableKey);
				     	}
				    });
				}
			},
			
			// 清除子Grid控件子表的选择
			clearChildGridSelect : function(childGridPara){
				childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				
				// 更新子表数据
				if(childGridPara!=null){
					var childs = childGridPara.split(":");
					childs.forEach(function(item){
				     	var childItem = item.split(",");
				     	if(childItem.length==4){
				     		var gridName = childItem[0];
				     		$itfreer_form_core.clearGridSelect(gridName);
				     	}
				    });
				}
			},
			
			// 获取Grid选择的记录集
			getGridSelect : function(gridName, gridKey, tableKey){
				var treeGridControl = $('#'+gridName);
				var dataList = [];
			    $("input:checked").each(function(){
			        var id = $(this).attr("id");
			        if(id && id.indexOf(gridName+'_')>-1){
			        	id = id.replace(gridName+'_','');
			        	var sData = treeGridControl.treegrid('find', id);
			        	if(gridKey!=null && tableKey!=null){
			        		var tData = {};
			        		tData[tableKey] = sData[gridKey];
			        		dataList.push(tData);
			        	}else{
			        		dataList.push(sData);
			        	}
			        }
			    });
			    return dataList;
			},
			
			// 设置子Grid控件子表的选择
			setChildSelect : function(gridName, tableData, gridKey, tableKey){
				$("input:checked").each(function(){
			        var id = $(this).attr("id");
			        if(id && id.indexOf(gridName+'_')>-1){
			        	$(this).attr("checked",false);
			        }
			    });
				
				if(gridKey!=null && tableKey!=null
						&& tableData!=null && tableData.length>0){
					var treeGridControl = $('#'+gridName);
					$("input:checkbox[name='"+gridName+"']").each(function(){
				        var id = $(this).attr("id");
				        var gid = id.replace(gridName+'_','');
			        	var gData = treeGridControl.treegrid('find', gid);
			        	var gValue = gData[gridKey];
			        	tableData.forEach(function(e){
							var tValue = e[tableKey];
							if(gValue == tValue){
								$("#"+id).attr("checked",true);
								return;
							}
						});
				    });
				}
			},
			
			// 清除子Grid控件的选择
			clearGridSelect : function(gridName){
				$("input:checked").each(function(){
			        var id = $(this).attr("id");
			        id = id ? id : '';
			        if(id.indexOf(gridName+'_')>-1){
			        	$(this).attr("checked",false);
			        }
			    });
			},
			
			// 删除实体
			delEntity : function(formName, row){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", "确定删除此记录?", function(r){
					if(r){
						row = row ? row : $formObject[formName].editRow;
						var rowMap = {};
						rowMap[$formObject[formName].keyField] = row[$formObject[formName].keyField];
						$itfreerHttp.deleteByKey($formObject[formName].tableName, rowMap,
							function(data){
								$rootScope.$apply(function() {
									$formObject[formName].editList.list.remove(row);
									$formObject[formName].editList.rowsCount -= 1;
									$itfreer_form_core.setSelectedRows($formObject[formName].editList.list);
								});
							}, 
							function(xhr){
								if(xhr.hasOwnProperty('responseText') 
										&& xhr.responseText!=null
										&& xhr.responseText!=''){
									if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
										$.messager.alert('系统提示', '删除失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
									}else{
										$.messager.alert('系统提示', '删除失败！原因：'+xhr.responseText);
									}
								}else{
									$.messager.alert('系统提示', '删除失败！原因：请求超时！');
								}
							}
						);
					}
				});
			},
			
			// 批量删除实体
			delEntitys : function(formName){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", "确定删除选择记录?", function(r){
					if(r){
						var rows = $formObject[formName].editList.list;
						if(rows==null){
							return;
						}
						
						if($formObject[formName].bmpKey){
							// 不可删除记录
							var noDelRows = [];
							rows.forEach(function(e){  
								if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
									if(e["TASK_CANDEL"]!="1"){
										noDelRows.push(e);
									}
								}
							});
							
							if(noDelRows.length>0){
								$.messager.confirm("操作确认", "选择的记录中有部分记录不能被删除。是否自动取消不可删除记录的选择?", function(r){
									if(r){
										$rootScope.$apply(function(){
											noDelRows.forEach(function(e){  
												e[$formObject.selectedField] = false;
											});
											$itfreer_form_core.setSelectedRows($formObject[formName].editList.list);
										});
									}
								});
								return;
							}
						}
						
						var keys = $formObject[formName].keyField+":in";
						var values = "";
						var dRows = [];
						rows.forEach(function(e){  
							if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
								if (typeof (e[$formObject[formName].keyField]) == 'string'){
									values += "'"+e[$formObject[formName].keyField] + "',";
								}else{
									values += e[$formObject[formName].keyField] + ",";
								}
								dRows.push(e);
							}
						});
						if(values!=""){
							values = values.substr(0, values.length-1);
							var rowMap = {};
							rowMap[keys] = values;
							if($formObject[formName].bmpKey){
								$itfreerHttp.deleteByKeyInBpm($formObject[formName].tableName, rowMap, $formObject[formName].bmpKey,
										function(data){
											if(dRows.length == $formObject[formName].editList.pageSize){
												$itfreer_form_core.innerLoadData(formName, true, false);
											}else{
												$rootScope.$apply(function() {
													dRows.forEach(function(e){  
														$formObject[formName].editList.list.remove(e);
													});
													$formObject[formName].editList.rowsCount -= dRows.length;
												});
											}
										}, 
										function(xhr){
											if(xhr.hasOwnProperty('responseText') 
													&& xhr.responseText!=null
													&& xhr.responseText!=''){
												if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
													$.messager.alert('系统提示', '删除失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
												}else{
													$.messager.alert('系统提示', '删除失败！原因：'+xhr.responseText);
												}
											}else{
												$.messager.alert('系统提示', '删除失败！原因：请求超时！');
											}
										}
									);
							}else{
								$itfreerHttp.deleteByKey($formObject[formName].tableName, rowMap,
										function(data){
											if(dRows.length == $formObject[formName].editList.pageSize){
												$itfreer_form_core.innerLoadData(formName, true, false);
											}else{
												$rootScope.$apply(function() {
													dRows.forEach(function(e){  
														$formObject[formName].editList.list.remove(e);
													});
													$formObject[formName].editList.rowsCount -= dRows.length;
												});
											}
										}, 
										function(xhr){
											if(xhr.hasOwnProperty('responseText') 
													&& xhr.responseText!=null
													&& xhr.responseText!=''){
												if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
													$.messager.alert('系统提示', '删除失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
												}else{
													$.messager.alert('系统提示', '删除失败！原因：'+xhr.responseText);
												}
											}else{
												$.messager.alert('系统提示', '删除失败！原因：请求超时！');
											}
										}
									);
							}
						}else{
							
						}
						$itfreer_form_core.setSelectedRows($formObject[formName].editList.list);
					}
				});
			},
			
			// 逻辑添加子表的空记录，但不提交到数据库中 childTable子表名称，keyField 子表主键
			addChildNewRow : function(formName, childTable, keyField){
				formName = formName ? formName : 'fd';
				if(!$formObject[formName].editRow.hasOwnProperty('childValues')){
					$formObject[formName].editRow.childValues = {};
				}
				if(!$formObject[formName].editRow.childValues[childTable]){
					$formObject[formName].editRow.childValues[childTable] = [];
				}
				var obj = {};
				var guid = $itfreer_core.getGUID();
				obj[keyField] = guid;
				obj[$formObject.isNew] = true;
				$formObject[formName].editRow.childValues[childTable].push(obj);
			},

			// 逻辑添加空记录，但不提交到数据库中 list数据列表，keyField 子表主键
			addNewRow : function(list, keyField){
				if(!list){
					list = [];
				}
				var obj = {};
				var guid = $itfreer_core.getGUID();
				obj[keyField] = guid;
				obj[$formObject.isNew] = true;
				list.push(obj);
			},
			
			// 设置子表编辑对象
			setChildEditRow : function(formName, row, keyField){
				formName = formName ? formName : 'fd';
				if(row!=null){
					var copyRow = jQuery.extend(true, {}, row);
					$formObject[formName].cOldRow = row;
					$formObject[formName].cEditRow = copyRow;
				}else{
					var guid = $itfreer_core.getGUID();
					row = {};
					row[keyField] = guid;
					row[$formObject.isNew] = true;
					$formObject[formName].cOldRow = null;
					$formObject[formName].cEditRow = row;
				}
			},
			
			// 逻辑批量删除，不提交到数据库
			delSelectedEntitys : function(rowList){
				if(rowList==null){
					return;
				}
				var dRows = [];
				rowList.forEach(function(e){  
					if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
						dRows.push(e);
					}
				});
				dRows.forEach(function(e){  
					rowList.remove(e);
				});
				$itfreer_form_core.setSelectedRows(rowList);
			},
			
			// 逻辑删除数据
			delEntityInList : function(rowList, row){
				rowList.remove(row);
				$itfreer_form_core.setSelectedRows(rowList);
			},
			
			// 逻辑保存子表记录，不保存到数据库
			saveChildRow : function(formName, childTableName, row, uniqueKey){
				formName = formName ? formName : 'fd';
				if($formObject[formName].cOldRow!=null){
					jQuery.extend(true, $formObject[formName].cOldRow, row);
				} else {
					if(!$formObject[formName].editRow.hasOwnProperty('childValues')){
						$formObject[formName].editRow.childValues = {};
					}
					if (!$formObject[formName].editRow.childValues[childTableName]) {
						$formObject[formName].editRow.childValues[childTableName] = [];
					};
					//按唯一条件删除子表重复记录
					if (uniqueKey) {
						for (var i = 0; i < $formObject[formName].editRow.childValues[childTableName].length; i++) {
							var item = $formObject[formName].editRow.childValues[childTableName][i];
							if (item[uniqueKey] && item[uniqueKey] == row[uniqueKey]) {
								$formObject[formName].editRow.childValues[childTableName].remove(item);
							};
						};
					};
					$formObject[formName].editRow.childValues[childTableName].push(row);
				}
			},

			// 初始化表单属性并加载数据
			initAndLoadGridData : function(formName, tableName, keyField, randomFields, 
					orderObject, formValue, queryValue, bmpKey, treeGirdName, 
					idField, pIDField, treeJBField, treeIsChildField, treeLoadJBs,
					childTables, childGridPara, tagetTableNames, childOrders){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.initTreePara(formName, tableName, keyField, randomFields, orderObject, 
						formValue, queryValue, bmpKey, treeGirdName, idField, pIDField, 
						treeJBField, treeIsChildField, treeLoadJBs,
						childTables, childGridPara, tagetTableNames, childOrders);
				$itfreer_form_core.loadTreeData(formName);
				if(bmpKey){
					$itfreer_form_core.loadBpmFormConfig(formName);
				}
			},
			
			// 内部树重新查询
			loadTreeData:function(formName){
				formName = formName ? formName : 'fd';
				var queryObject = jQuery.extend(true, $formObject[formName].queryObject, $formObject[formName].queryValue);
				$itfreerHttp.getTreeData($formObject[formName].tableName, queryObject, 
						$formObject[formName].orderObject, '', $formObject[formName].treeLoadJBs,'', 
						$formObject[formName].editList.pageSize, $formObject[formName].editList.pageIndex, false,
					function(treedata) {
						treedata = treedata ? treedata : [];
						$rootScope.$apply(function() {
							var treeGridControl = $('#'+$formObject[formName].treeGirdName);
							treeGridControl.treegrid('loadData', treedata);
						});
					}, function(ex) { }
				);
			},
			
			// 设置查询条件并查询
			setTreeQueryObjectAndQuery:function(formName, field, value){
				formName = formName ? formName : 'fd';
				if(value==null || value == "null"){
					if($formObject[formName].queryObject.hasOwnProperty(field)){
						delete $formObject[formName].queryObject[field];
					}
				}else{
					$formObject[formName].queryObject[field]=value;
				}
				$itfreer_form_core.loadTreeData(formName);
			},
			
			// 设置排序对象
			setTreeOrderObjectAndQuery:function(formName, field, value){
				formName = formName ? formName : 'fd';
				if(value==null || value == "null"){
					if($formObject[formName].orderObject.hasOwnProperty(field)){
						delete $formObject[formName].orderObject[field];
					}
				}else{
					$formObject[formName].orderObject[field]=value;
				}
				$itfreer_form_core.loadTreeData(formName);
			},
			
			// 设置分页索引并且重新查询数据
			setTreePageIndexAndQuery:function(formName, pageIndex){
				formName = formName ? formName : 'fd';
				$formObject[formName].editList.pageIndex = pageIndex;
				$itfreer_form_core.loadTreeData(formName);
			},
			
			//上一页
			preTreePage:function(formName){
				formName = formName ? formName : 'fd';
				var pageIndex = $formObject[formName].editList.pageIndex;
				pageIndex--;
				if(pageIndex<=0){
					pageIndex =1 ;
				}
				$itfreer_form_core.setTreePageIndexAndQuery(formName, pageIndex);
			},
			
			//下一页
			nextTreePage:function(formName){
				formName = formName ? formName : 'fd';
				var pageIndex = $formObject[formName].editList.pageIndex;
				var pageCount = $formObject[formName].editList.pageCount;
				pageIndex++;
				if(pageIndex>pageCount){
					pageIndex = pageCount ;
				}
				$itfreer_form_core.setTreePageIndexAndQuery(formName, pageIndex);
			},
			
			//首页
			firstTreePage:function(formName){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.setTreePageIndexAndQuery(formName, 1);
			},
			
			//尾页
			lastTreePage:function(formName){
				formName = formName ? formName : 'fd';
				var pageCount = $formObject[formName].editList.pageCount;
				$itfreer_form_core.setTreePageIndexAndQuery(formName, pageCount);
			},

			// 添加树型数据的下级编辑记录
			addTreeNextEditRow:function(formName){
				formName = formName ? formName : 'fd';
				var treeGridControl = $('#'+$formObject[formName].treeGirdName);
				var selectedNode = treeGridControl.treegrid('getSelected');
				if(selectedNode==null){
					$.messager.alert('系统提示', '请选择一个父节点！');
					return;
				}
				
				var row = null;
				if($formObject[formName].hasOwnProperty("defaultObject")){
					row = jQuery.extend(true, {}, $formObject[formName].defaultObject);
				}else{
					row = {};
				}
				row[$formObject.isNew]=true;
				row[$formObject[formName].pIDField] = selectedNode[$formObject[formName].idField];
				$formObject[formName].editRow = row;
				
				// 有工作流，处理流程配置信息
				if($formObject[formName].bmpKey){
					$itfreer_form_core.loadBpmTaskFormConfig(formName, row);
					$itfreer_form_core.setBpmTaskConfig(formName, row);
				}
			},
			
			// 编辑当前选择的树节点
			editTreeSelectedRow:function(formName, childTables){
				formName = formName ? formName : 'fd';
				var treeGridControl = $('#'+$formObject[formName].treeGirdName);
				var row = treeGridControl.treegrid('getSelected');
				if(row==null){
					$.messager.alert('系统提示', '请选择一个节点！');
					return;
				}
				$itfreer_form_core.setEditRow(formName, row, childTables, null, null, null);
			},
			
			// 删除当前选择的树节点
			delTreeSelectedRows:function(formName, tableName, row){
				formName = formName ? formName : 'fd';
				var treeGridControl = $('#'+$formObject[formName].treeGirdName);
				row = row ? row : treeGridControl.treegrid('getSelected');
				if(row==null){
					$.messager.alert('系统提示', '请选择一个节点！');
					return;
				}
				
				$.messager.confirm("操作确认", "确定删除此记录?", function(r){
					if(r){
						tableName = tableName ? tableName : $formObject[formName].tableName;
						
						var rowMap = {};
						rowMap[$formObject[formName].keyField] = row[$formObject[formName].keyField];
						$itfreerHttp.deleteByKey(tableName, rowMap,
							function(data){
								var pid = row[$formObject[formName].idField];
								// 看有没有上级
								var parentNode = treeGridControl.treegrid('getParent',pid);
								if(parentNode!=null){
									var id = parentNode[$formObject[formName].idField];
									var nodes = treeGridControl.treegrid('getChildren', id);
									if( (nodes==null || nodes.length <=1) && parentNode[$formObject[formName].treeIsChildField] == "0" ){
										parentNode[$formObject[formName].treeIsChildField] = "1";
										$itfreerHttp.save(tableName, parentNode,
											function(data){
												treeGridControl.treegrid('refresh',id); 
											}, 
											function(ex){ } );
									}
								}
								treeGridControl.treegrid('remove',pid);
								//alert('删除成功！');
							}, 
							function(xhr){
								if(xhr.hasOwnProperty('responseText') 
										&& xhr.responseText!=null
										&& xhr.responseText!=''){
									if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
										$.messager.alert('系统提示', '删除失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
									}else{
										$.messager.alert('系统提示', '删除失败！原因：'+xhr.responseText);
									}
								}else{
									$.messager.alert('系统提示', '删除失败！原因：请求超时！');
								}
							}
						);
					}
				});
			},

			// 保存实体
			save : function(formName, tableName, row, byBpmSave, bmpObject, childGridPara, successFunction, failFunction){
				formName = formName ? formName : 'fd';
				if($formObject.isOptioning){
					$.messager.alert("系统提示","系统处理中，请稍等！");
					return;
				}
				$formObject.isOptioning = true;

				childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				tableName = tableName ? tableName : $formObject[formName].tableName;
				row = row ? row : $formObject[formName].editRow;
				
				// 处理Grid选择子表，其它的不需要处理，因为子表数据就在数据中
				$formObject[formName].editRow.childValues = $formObject[formName].editRow.childValues ? $formObject[formName].editRow.childValues : {};
				// 更新子表数据
				if(childGridPara!=null){
					var childs = childGridPara.split(":");
					childs.forEach(function(item){
				     	var childItem = item.split(",");
				     	if(childItem.length==4){
				     		var gridName = childItem[0];
				     		var childTableName = childItem[1];
				     		var gridKey = childItem[2];
				     		var tableKey = childItem[3];
				     		
				     		if($formObject[formName].editRow.childValues.hasOwnProperty(childTableName) && $("#gridName").length > 0){
				     			delete $formObject[formName].editRow.childValues[childTableName];
							}
				     		if($("#"+gridName).length > 0){
				     			var childData = $itfreer_form_core.getGridSelect(gridName, gridKey, tableKey);
					     		$formObject[formName].editRow.childValues[childTableName] = childData;
				     		}
				     	}
				    });
				}
				
				// 处理自动增值键
				if(row[$formObject[formName].keyField]==null || row[$formObject[formName].keyField]==""){
					var guid = $itfreer_core.getGUID();
					row[$formObject[formName].keyField] = guid;
				}
				
				// 处理随机赋值字段
				if($formObject[formName].randomFields){
					for (var i = 0; i < $formObject[formName].randomFields.length; i++) {
						var randomField = $formObject[formName].randomFields[i];
						if (row[randomField]==null || row[randomField]=="") {
							var randomValue = $itfreer_core.getGUID();
							row[randomField] = randomValue;
						};
					};
				}
				
				// 处理工作流定义ID
				if($formObject[formName].bmpKey != null && $formObject[formName].bmpKey != ""){
					row["ACTIVITIKEY"] = $formObject[formName].bmpKey;
				} else {
					row["ACTIVITIKEY"] = "";
				}
				
				// 是否工作流保存操作
				if(byBpmSave){
					row["ACTIVITISAVE"] = "1";
				} else {
					row["ACTIVITISAVE"] = "0";
				}
				
				// 处理工作流默认对象
				if(bmpObject != null){
					// 复制对象中的值
					row = $.extend(row, bmpObject); 
				}
				
				// 处理下一节点审批人信息
				if($formObject.nextAssignees.length>0){
					var taskString = "";
					var isReturn = false;
					$formObject.nextAssignees.forEach(function(taskItem){
						// 任务key,user1,username:任务key,user1,username
				     	var taskid = taskItem.taskid;
				     	var taskname = taskItem.taskname;
				     	taskString += taskid + ",";
				     	var findUser = false;
				     	taskItem.data.forEach(function(dateItem){
				     		if(dateItem.checked == "1"){
				     			var userid = dateItem.id;
				     			var username = dateItem.text;
				     			
				     			taskString += userid + ",";
				     			taskString += username + ",";
				     			findUser = true;
				     		}
				     	});
				     	if(findUser){
				     		taskString = taskString.substring(0, taskString.length-1);
				     		taskString += ":";
				     	}else{
				     		$.messager.alert('系统提示', "【"+taskname+"】节点未指定审批用户！");
				     		isReturn = true;
				     		return;
				     	}
				    });
					if(isReturn){
						return;
					}
					taskString = taskString.substring(0, taskString.length-1);
					row["TASKUSER"] = taskString;
				}
				
				if($formObject.nextTasks.length>0){
					var tjTasks = "";
					for(var i=0;i<$formObject.nextTasks.length;i++){
						if($formObject.nextTasks[i].checked == "1"){
							tjTasks += $formObject.nextTasks[i].id + ",";
						}
					}
					if(tjTasks==""){
						$.messager.alert('系统提示', "至少得选择一个提交节点！");
			     		return;
					}
					tjTasks = tjTasks.substring(0, tjTasks.length-1);
					row["TJTASKS"] = tjTasks;
				}
				
				// 处理交办信息
				if($formObject.bpmJb.userid!="" && $formObject.bpmJb.username!=""){
					row["JBUSER"] = $formObject.bpmJb.userid + "," + $formObject.bpmJb.username;
				}
				
				// 处理treeGrid的添加顶级和添加下级事项
				var node = null;
				var treeGridControl = null;
				if($formObject[formName].treeGirdName 
						&& $formObject[formName].treeGirdName!=""){
					treeGridControl = $('#'+$formObject[formName].treeGirdName);
					node = treeGridControl.treegrid('getSelected');
					// 添加顶级项
					if(row[$formObject[formName].pIDField] == null){
						row[$formObject[formName].treeJBField] = 1;
						row[$formObject[formName].treeIsChildField] = "1";
					} else {
						// 添加下级项
						if(row[$formObject[formName].idField] != node[$formObject[formName].idField]){
							var level = treeGridControl.treegrid('getLevel', node[$formObject[formName].idField]);
							row[$formObject[formName].treeJBField] = level + 1;
							row[$formObject[formName].treeIsChildField] = "1";
						}
					}
				}
				$itfreerHttp.save(tableName, row,
						function(data){
					// 表单保存的拦截未通过
					if(data.unpass && data.unpass.length>0){
						if(failFunction!=null){
							failFunction(data);
						}
					} else {
						$rootScope.$apply(function() {
							
							$itfreer_form_core.doChilds(data);

							if(row.hasOwnProperty("childValues")){
								delete row["childValues"];
							}
							jQuery.extend(true, row, data);
							
							// 处理新对象无刷插入
							if(row[$formObject.isNew]==null || row[$formObject.isNew]==true){
								// 新对象，插入
								row[$formObject.isNew] = false;
								if(!$formObject[formName].hasOwnProperty("editList")){
									$formObject[formName].editList = {};
								}
								if(!$formObject[formName].editList.hasOwnProperty("list")){
									$formObject[formName].editList.list = [];
								}
								$formObject[formName].editList.list.unshift(row);
								$formObject[formName].editList.rowsCount += 1;
								
								// 如果treeGrid不为空，说明是树操作
								if($formObject[formName].treeGirdName 
										&& $formObject[formName].treeGirdName != ""){
									var datas = [];
									datas.push(row);
									var treeGridControlEx = $('#'+$formObject[formName].treeGirdName);
									// 添加顶级项
									if(row[$formObject[formName].pIDField] == null){
										treeGridControlEx.treegrid('append',{
											parent: null,  data: datas });
									} else {
										// 添加下级项
										treeGridControlEx.treegrid('append',{
											parent: node[$formObject[formName].idField], data: datas });
										// 处理上级的数据
										if(node[$formObject[formName].treeIsChildField] == "1"){
											node[$formObject[formName].treeIsChildField] = "0";
											$itfreerHttp.save(tableName, node,
													function(data){
												treeGridControlEx.treegrid('refresh',node[$formObject[formName].idField]); 
											}, 
											function(ex){ } );
										}
									}
								}
							}else{
								// 更新对象
								if($formObject[formName].curOldRow){
									if($formObject[formName].curOldRow.hasOwnProperty("childValues")){
										delete $formObject[formName].curOldRow["childValues"];
									}
									jQuery.extend(true, $formObject[formName].curOldRow, data);
								}
								if($formObject[formName].treeGirdName 
										&& $formObject[formName].treeGirdName != ""){
									// 更新树对象，不处理子节点与级别
									var treeGridControl = $('#'+$formObject[formName].treeGirdName);
									treeGridControl.treegrid('refresh', data[$formObject[formName].idField]);
								}
							}

							// 有工作流，处理流程配置信息
							if($formObject[formName].bmpKey){
								$itfreer_form_core.loadBpmTaskFormConfig(formName, data);
								$itfreer_form_core.setBpmTaskConfig(formName, data);
							}
						
						});
						
						if(successFunction!=null){
							successFunction();
						}
						//alert('保存成功！');
					}
					$formObject.isOptioning = false;
				}, function(xhr,textStatus){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '保存失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '保存失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '保存失败！原因：请求超时！');
						}
						
						if(failFunction!=null){
							failFunction();
						}
						$formObject.isOptioning = false;
					}
				);
			},
			
			// 将数据的子表数据处理为旧数据 $formObject.isNew = false;
			doChilds : function(row){
				if(!row.hasOwnProperty('childValues')){
					return;
				}
				for(attribute in row.childValues){ 
				     var datas = row.childValues[attribute];
				     datas.forEach(function(ed){
				     	ed[$formObject.isNew] = false;
				     });
				     break;
				}
			},
			
			// 保存实体集
			saveEntitys : function(rows, formName){
				formName = formName ? formName : 'fd';
				$itfreerHttp.saveList($formObject[formName].tableName, rows,
					function(data){
						$.messager.alert('系统提示', '保存成功！');
					}, 
					function(xhr,textStatus){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '保存失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '保存失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '保存失败！原因：请求超时！');
						}
					}
				);
			},

			// 设置全选 checkName:checked控件名称，rowList:要选择的数据列表对象,field:选择的字段，默认为selectedField
			setAllSelected : function(checkName, rowList, field, trueValue, falseValue){
				field = field ? field : $formObject.selectedField;
				var checked = $("#"+checkName).attr("checked") == "checked";
				var checkedValue = null;
				if(checked){
					checkedValue = trueValue ? trueValue : checked;
				}else{
					checkedValue = falseValue ? falseValue : checked;
				}
				if(rowList.hasOwnProperty("list")){
					rowList.checkedRow = null;
					rowList.checkedRows = [];
					rowList.list.forEach(function(e){  
					    e[field] = checkedValue;
					    if(checked){
					    	rowList.checkedRows.push(e);
					    }
					});
					if(rowList.checkedRows.length==1){
						rowList.checkedRow = rowList.checkedRows[0];
					}
				} else {
					rowList.forEach(function(e){
					    e[field] = checkedValue;
					});
				}
			},
			
			// 根据rowList中的数据选择情况，重新处理rowList.checkedRows和rowList.checkedRow值。
			setSelectedRows : function(rowList){
				if(rowList.hasOwnProperty("list")){
					rowList.checkedRow = null;
					rowList.checkedRows = [];
					rowList.list.forEach(function(e){  
					    var checked = e[$formObject.selectedField];
					    if(checked){
					    	rowList.checkedRows.push(e);
					    }
					});
					if(rowList.checkedRows.length==1){
						rowList.checkedRow = rowList.checkedRows[0];
					}
				}
			},
			
			// 选择或取消选择，rowList：数据列表,row:需选择数据,onlySelect:是否只选择指定数据
			selectRow : function(rowList, row, onlySelect){
				var checked = !row.hasOwnProperty($formObject.selectedField) || !row[$formObject.selectedField];
				if(rowList.hasOwnProperty("list")){
					if(onlySelect){
						rowList.list.forEach(function(e){
							if(row!=e){
								e[$formObject.selectedField]=false;
							}
						});
						rowList.checkedRows = [];
						if(checked){
							rowList.checkedRow = row;
							rowList.checkedRows.push(row);
						}else{
							rowList.checkedRow = null;
						}
					}else{
						rowList.checkedRows = [];
						rowList.list.forEach(function(e){
							if(row!=e 
									&& e.hasOwnProperty($formObject.selectedField)
									&& e[$formObject.selectedField]){
								rowList.checkedRows.push(e);
							}
						});
						if(checked){
							rowList.checkedRows.push(row);
						}
						if(rowList.checkedRows.length==1){
							rowList.checkedRow = rowList.checkedRows[0];
						}else{
							rowList.checkedRow = null;
						}
					}
				}else{
					if(onlySelect){
						rowList.forEach(function(e){
							if(row!=e){
								e[$formObject.selectedField]=false;
							}
						});
					}
				}
			},

			// word导出
			exportDoc : function(dataMap, flt, fileName) {
				$itfreerHttp.exportDoc(dataMap, flt, fileName,
					function(data){
						var url = getBasePath() + "/" + data;
						window.open(url);
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '导出失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '导出失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '导出失败！原因：请求超时！');
						}
					}
				);
			},

			// 工作流中的撤销，交办等保存工作
			saveByBpm : function(msg, formName, row, byBpmSave, bmpObject, childGridPara, successFunction, failFunction){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", '确定'+msg+'吗?', function(r){
					if(r){
						$formObject.nextAssignees = [];
						$formObject.nextTasks = [];
						$itfreer_form_core.save(formName, null, row, byBpmSave, bmpObject, childGridPara, successFunction, failFunction);
					}
				});
			},
			
			// 工作流定义的挂起与激活
			suspendOrActivateByBpm : function(msg, type, formName, row){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", '确定'+msg+'吗?', function(r){
					if(r){
						row = row ? row : $formObject[formName].editRow;
						if(row==null){
							return;
						}
						if(row["TASK_DEFINID"] == null
								|| row["TASK_DEFINID"] == ""){
							return;
						}
						var id = row["TASK_DEFINID"];
						$itfreerHttp.suspendOrActivateByBpm(id,type,
							function(data){
								$.messager.alert('系统提示', data.result);
							}, 
							function(xhr){
								 if(xhr.hasOwnProperty('responseText') 
								 		&& xhr.responseText!=null
								 		&& xhr.responseText!=''){
								 	$.messager.alert('系统提示', '审批历史失败！原因：'+xhr.responseText);
								 }
							}
						);
					}
				});
			},

			// 工作流实例的挂起与激活
			suspendOrActivateByInst : function(msg, type, formName, row){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", '确定'+msg+'吗?', function(r){
					if(r){
						row = row ? row : $formObject[formName].editRow;
						$formObject.historyRow = [];
						if(row==null){
							return;
						}
						if(row["TASK_PROID"] == null
								|| row["TASK_PROID"] == ""){
							return;
						}
						var id = row["TASK_PROID"];
						var bussId = row["GUID"];
						$itfreerHttp.suspendOrActivateByInst(id,type,bussId,
							function(data){
								
							}, 
							function(xhr){
								 if(xhr.hasOwnProperty('responseText') 
									 		&& xhr.responseText!=null
									 		&& xhr.responseText!=''){
									 	$.messager.alert('系统提示', '审批历史失败！原因：'+xhr.responseText);
								 }
							}
						);
					}
				});
			},

			// 流程第一次提交时，先做保存，再做提交，来解决第一次提交时不能提示用户确认第二个节点的审批用户信息
			saveByFirst : function(formName, row, bmpObject, childGridPara, 
				successFunction, failFunction){
				formName = formName ? formName : 'fd';
				if(!row){
					$.messager.alert('系统提示','表单值收集错误！');
					return;
				}

				if(!row.hasOwnProperty($formObject.isNew) 
					|| row[$formObject.isNew] == null
					|| row[$formObject.isNew] == true){
					$.messager.confirm("操作确认", '确定提交吗?', function(r){
						if(r){
							$formObject.nextAssignees = [];
							$formObject.nextTasks = [];
							// 先保存
							$itfreer_form_core.save(formName, null, row, false, 
								bmpObject, childGridPara, function(data){
								if(successFunction){
									successFunction();
								}
							}, failFunction);
						}
					});
				}else{
					if(successFunction){
						successFunction();
					}
				}
			},

			// 加载工作流的表单配置信息
			loadBpmFormConfig : function(formName){
				formName = formName ? formName : 'fd';
				if($formObject[formName].hasOwnProperty("bpmFormList")
						&& typeof($formObject[formName].bpmFormList) != "undefined"
						&& $formObject[formName].bpmFormList != null){
					return;
				}
				
				// 定义当前工作流的表单配置信息
				$formObject[formName].bpmFormList = null;
				$itfreerHttp.getBpmForms($formObject[formName].bmpKey,
					function(data){
						$formObject[formName].bpmFormList = data;
						
						// 数据加载后，如果需要处理流程对象
						if(typeof($formObject[formName].bpmFormList) != "undefined"
							&& $formObject[formName].bpmFormList != null
							&& typeof($formObject[formName].bpm) != "undefined"
							&& $formObject[formName].bpm != null
							&& $formObject[formName].bpm.hasOwnProperty("row")
							&& typeof($formObject[formName].bpm.row) != "undefined"
							&& $formObject[formName].bpm.row != null){
							$rootScope.$apply(function() {
								$itfreer_form_core.loadBpmTaskFormConfig(formName, $formObject[formName].bpm.row);
								$itfreer_form_core.setBpmTaskConfig(formName, $formObject[formName].bpm.row);
							});
						}
					}, 
					function(xhr){
						// if(xhr.hasOwnProperty('responseText') 
						// 		&& xhr.responseText!=null
						// 		&& xhr.responseText!=''){
						// 	if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
						// 		$.messager.alert('系统提示', '流程表单配置获取失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
						// 	}else{
						// 		$.messager.alert('系统提示', '流程表单配置获取失败！原因：'+xhr.responseText);
						// 	}
						// }else{
						// 	$.messager.alert('系统提示', '流程表单配置获取失败！原因：请求超时！');
						// }
					}
				);
			},
			
			// 加载工作流当前节点的表单配置信息
			loadBpmTaskFormConfig : function(formName, row){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				$formObject[formName].bpm = {};
				
				if(typeof($formObject[formName].bpmFormList) == "undefined"
					|| $formObject[formName].bpmFormList == null){
					$formObject[formName].bpm.row = row;
					return;
				}
				
				var id = "";
				if(row != null
						&& row["TASK_TASKID"] != null
						&& row["TASK_TASKID"] != ""){
					id = row["TASK_TASKID"];
				} else {
					id = "U0";
				}
				
				// 当前任务的审批人信息
				var taskAssig = row["TASK_ASSIGNEES"];
				if(taskAssig==null || taskAssig==""){
					taskAssig = "";
				}
				// 任务：审批人信息
				var tasks = taskAssig.split(":");
				var userid = $formObject.user.userid;
				userid = userid ? userid : "-1";
				
				var ids = id.split(",");
				var allObject = {};
				for(var i=0;i<ids.length;i++){
					id = ids[i];
					if(!$formObject[formName].bpmFormList.hasOwnProperty(id)){
						continue;
					}
					
					// 查看当前人是不是有可编辑权限
					var canAu = true;
			    	if(userid != "-1" && tasks.length>0){
			    		for(var j=0; j<tasks.length; j++){
			    			var users = tasks[j].split(",");
			    			var taskId = users[0];
			    			if(id == taskId){
			    				var isau = tasks[j].indexOf(userid, 0);
				    			if(isau<0){
				    				canAu = false;
				    			}
				    			break;
			    			}
			            }
			    	}
					if(!canAu){
						continue;
					}
					var bpmObject = $formObject[formName].bpmFormList[id];
					for(obj in bpmObject){ 
						if(!allObject.hasOwnProperty(obj)){
							allObject[obj] = bpmObject[obj];
						}else{
							var objValue = allObject[obj] || bpmObject[obj];
							allObject[obj] = objValue;
						}
					}
				}
				$formObject[formName].bpm = allObject;
				$itfreer_form_core.loadBpmTaskTabConfig(formName, row);
			},
			
			// 加载工作流当前节点的Tab配置信息
			loadBpmTaskTabConfig : function(formName, row){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				if($formObject[formName].bpmFormList==null){
					return;
				}
				
				var id = "";
				if(row != null
						&& row["TASK_TASKID"] != null
						&& row["TASK_TASKID"] != ""){
					id = row["TASK_TASKID"];
				} else {
					id = "U0";
				}
				
				var ids = id.split(",");
				if(ids.length==1){
					var id = ids[0];
					if(!$formObject[formName].bpmFormList.hasOwnProperty(id)){
						return;
					}
					var bpmObject = $formObject[formName].bpmFormList[id];
					if(bpmObject.hasOwnProperty("_showTab")){
						var tabMsgs = bpmObject["_showTab"].split('.');
						if(tabMsgs.length==2){
							$itfreer_form_core.setTab(tabMsgs[0], tabMsgs[1]);
						}
					}
				}else{
					var taskAssig = row["TASK_ASSIGNEES"];
					if(taskAssig==null || taskAssig==""){
						taskAssig = "";
					}
					var tasks = taskAssig.split(":");
					if(tasks.length>1){
			    		for(var j=0; j<tasks.length; j++){
			    			var users = tasks[j].split(",");
			    			var id = users[0];
			    			if(!$formObject[formName].bpmFormList.hasOwnProperty(id)){
		    					continue;
		    				}
		    				var bpmObject = $formObject[formName].bpmFormList[id];
		    				if(bpmObject.hasOwnProperty("_showTab")){
		    					var tabMsgs = bpmObject["_showTab"].split('.');
		    					if(tabMsgs.length==2){
		    						$itfreer_form_core.setTab(tabMsgs[0], tabMsgs[1]);
		    					}
		    					return;
		    				}
			            }
			    	}
				}
			},
			
			// 加载工作流审批历史和流程图
			loadHistoryAndImage : function(formName, row, iboxName){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.loadHistoryRow(formName, row);
				$itfreer_form_core.showBpmImage(formName, row, iboxName);
			},
			
			// 加载工作流审批历史
			loadHistoryRow : function(formName, row){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				
				$formObject.historyRow = [];
				if(row==null){
					return;
				}
				if(row["TASK_PROID"] == null
						|| row["TASK_PROID"] == ""){
					return;
				}
				var id = row["TASK_PROID"];
				$itfreerHttp.getBpmHistory(id,
					function(data){
						$rootScope.$apply(function() {
							$formObject.historyRow = data;
						});
					}, 
					function(xhr){
						// if(xhr.hasOwnProperty('responseText') 
						// 		&& xhr.responseText!=null
						// 		&& xhr.responseText!=''){
						// 	if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
						// 		$.messager.alert('系统提示', '审批历史失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
						// 	}else{
						// 		$.messager.alert('系统提示', '审批历史失败！原因：'+xhr.responseText);
						// 	}
						// }else{
						// 	$.messager.alert('系统提示', '审批历史失败！原因：请求超时！');
						// }
					}
				);
			},
			
			// 显示流程图  row : 流程业务数据，iboxName : 弹窗名称
			showBpmImage : function(formName, row, iboxName){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				iboxName = iboxName ? iboxName : 'bpm';
				
				if(row==null){
					$.messager.alert('系统提示', '请选择需要查看的数据！');
					return;
				}
				if(row["TASK_PROID"] == null
						|| row["TASK_PROID"] == ""){
					$.messager.alert('系统提示', '请先发启流程！');
					return;
				}
				var id = row["TASK_PROID"];
				var loadSrc = getBasePath()+"/style/images/load.gif";
				$('#'+iboxName+'_img').attr("src", loadSrc);
				var guid = $itfreer_core.getGUID();
				var src=getBasePath()+"/workflow/exeimage.do?definitionId="+$formObject[formName].bmpKey+"&executionId="+id+"&guid="+guid;
				$('#'+iboxName+'_img').attr("src", src);
				$itfreer_form_core.openWindow(iboxName);
			},
			
			// 设置当前工作流的节点配置信息，主要是当前节点的审批人，下一节点信息
			setBpmTaskConfig : function(formName, row){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				// 设置下一接点
				$formObject.nextAssignees = [];
				var taskAssigness =  row["TASK_NEXTASSIGNEES"];
				if(taskAssigness==null || taskAssigness==""){
					$formObject.nextAssignees = [];
				} else {
					$formObject.nextAssignees = [];
					var taskes = taskAssigness.split(":");
					taskes.forEach(function(item){
						var taskItemString = item.split(",");
						var taskItem = {};
						taskItem.taskid = taskItemString[0];
						taskItem.taskname = taskItemString[1];
						var taskUsers = [];
						for(var i=2;i<taskItemString.length;i+=2){
							var dateItem = {};
							dateItem.id = taskItemString[i];
							dateItem.text = taskItemString[i+1];
							dateItem.checked = "1";
							taskUsers.push(dateItem);
						}
						taskItem.data = taskUsers;
						$formObject.nextAssignees.push(taskItem);
					});
				}
				// 设置提交节点
				$formObject.nextTasks = [];
				var taskAssig = row["TASK_ASSIGNEES"];
				if(taskAssig==null || taskAssig==""){
					taskAssig = "";
				}
				var tasks = taskAssig.split(":");
				
		    	if(tasks.length>1){
		    		var userid = $formObject.user.userid;
		    		userid = userid ? userid : "-1";
		    		
		    		for(var j=0; j<tasks.length; j++){
		    			var users = tasks[j].split(",");
		    			var taskObject = {};
		    			taskObject.id = users[0];
		    			taskObject.text = users[1];
		    			taskObject.checked = "1";
		    			
		    			if(userid=="-1"){
		    				$formObject.nextTasks.push(taskObject);
		    			}else{
		    				var isau = tasks[j].indexOf(userid, 0);
		        			if(isau>=0){
		        				$formObject.nextTasks.push(taskObject);
		        			}
		    			}
		            }
		    	}
			},
			
			// 判断当前用户是否可审批数据节点
			isAU : function(formName){
				formName = formName ? formName : 'fd';
				var assigneeUser = $formObject[formName].editRow["TASK_ASSIGNEES"];
				if(assigneeUser==null || assigneeUser==""){
					return true;
				}
				var userid = $formObject.user.userid;
				if(userid==null || userid==""){
					return false;
				}
				if(userid=="-1"){
					return true;
				}
				var isau = assigneeUser.indexOf(userid, 0);
				return isau>=0;
			},
			
			// 判断当前用户是否可主动已提交的流程
			isCh : function(formName){
				formName = formName ? formName : 'fd';
				var assigneeUser = $formObject[formName].editRow["TASK_PTASKUSER"];
				if(assigneeUser==null || assigneeUser==""){
					return false;
				}
				var userid = $formObject.user.userid;
				if(userid==null || userid==""){
					return false;
				}
				
				var historys = assigneeUser.split("&");
				var last = historys[historys.length-1];
				var lastMsg = last.split("~");
				var taskUserMsg = lastMsg[0];
				var taskUser = taskUserMsg.split(",");
				if(userid==taskUser[2]){
					return true;
				}else{
					return false;
				}
			},

			// 自动保存流程配置
			autoSaveTask : function(formName, pdId) {
				formName = formName ? formName : 'fd';
				$itfreerHttp.autoSaveTask(pdId,
					function(data){
						$rootScope.$apply(function() {
							var row = data;
							row[$formObject.isNew] = false;
							$itfreer_form_core.doChilds(row);
							$formObject[formName].editList.list.unshift(row);
						});
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '创建失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '创建失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '创建失败！原因：请求超时！');
						}
					}
				);
			},

			// 加载表单，并打开表单
			// formUrl:表单地址，popName:弹窗名称，formName:表单名称, row:表单编辑的数据
			// <param name="defaultValueFun" type="Funciton" >表单默认值处理回调函数</param>
			openForm : function(formUrl, popName, formName, row, defaultValueFun){
				formName = formName ? formName : 'fd';
				if(defaultValueFun){
					row = defaultValueFun(row);
				}
				if(formUrl != $location.path()){
					$formObject.tempObject.openFormKey = "openForm";
					$formObject.tempObject.popName = popName;
					$formObject.tempObject.formName = formName;
					$formObject.tempObject.data = row;
					
					$location.path(formUrl);
					$location.replace();
				}else{
					$itfreer_form_core.setEditRow(formName, row);			
					$itfreer_form_core.openPop(popName);
				}
			},
			
			// formUrl:表单地址，popName:弹窗名称，formName:表单名称, row:表单编辑的数据
			openFormByKey : function(formUrl, popName, formName, tableName, key, defaultValueFun){
				formName = formName ? formName : 'fd';
				if(formUrl != $location.path()){
					$formObject.tempObject.openFormKey = "openFormByKey";
					$formObject.tempObject.popName = popName;
					$formObject.tempObject.formName = formName;
					$formObject.tempObject.tableName = tableName;
					$formObject.tempObject.formDataKey = key;
					$formObject.tempObject.defaultValueFun = defaultValueFun;
					
					$location.path(formUrl);
					$location.replace();
				}else{
					$itfreerHttp.getEntityByKey(tableName, key,
						function(data){
							$rootScope.$apply(function() {
								if(defaultValueFun){
									data = defaultValueFun(data);
								}
								$itfreer_form_core.setEditRow(formName, data);
							});
						}, 
						function(xhr){ }
					);
				}
			},

			// 销毁表单
			destroyForm : function(){
				// 删除当前的表单数据
				if($formObject.formNames.length>0){
					for(var i=0;i<$formObject.formNames.length;i++){
						var formName = $formObject.formNames[i];
						if($formObject.hasOwnProperty(formName)){
							delete $formObject[formName];
						}
					}
				}
				$formObject.formNames = [];
			},

			// easy ui
			destroyEasyui : function(){
				// 销毁easy ui对象
				if($formObject.windows.length>0){
					for(var i=0;i<$formObject.windows.length;i++){
						try{
							var pw = $formObject.windows[i];
							pw.window("destroy");
						}catch(e){}
					}
				}
				$formObject.windows = [];

				// 销毁easy ui对象
				if($formObject.combotrees.length>0){
					for(var i=0;i<$formObject.combotrees.length;i++){
						try{
							var pw = $formObject.combotrees[i];
							pw.combotree("destroy");
						}catch(e){}
					}
				}
				$formObject.combotrees = [];

				// 销毁easy ui对象
				if($formObject.comboboxs.length>0){
					for(var i=0;i<$formObject.comboboxs.length;i++){
						try{
							var pw = $formObject.comboboxs[i];
							pw.combobox("destroy");
						}catch(e){}
					}
				}
				$formObject.comboboxs = [];

				// 销毁easy ui对象
				if($formObject.treegrids.length>0){
					for(var i=0;i<$formObject.treegrids.length;i++){
						try{
							var pw = $formObject.treegrids[i];
							pw.treegrid("destroy");
						}catch(e){}
					}
				}
				$formObject.treegrids = [];

				// 销毁easy ui对象
				if($formObject.dateboxs.length>0){
					for(var i=0;i<$formObject.dateboxs.length;i++){
						try{
							var pw = $formObject.dateboxs[i];
							pw.datebox("destroy");
						}catch(e){}
					}
				}
				$formObject.dateboxs = [];
				// 销毁easy ui对象
				if($formObject.datetimeboxs.length>0){
					for(var i=0;i<$formObject.datetimeboxs.length;i++){
						try{
							var pw = $formObject.datetimeboxs[i];
							pw.datetimebox("destroy");
						}catch(e){}
					}
				}
				$formObject.datetimeboxs = [];
			}
		};
		for(f in $itfreer_form_core){
			$rootScope[f] = $itfreer_form_core[f];
		}
		$rootScope.formObject = $formObject;
		return $itfreer_form_core;
	});

	/**
	 * 表单第一个控制器
	 */
	itfreerformcoreModule.controller('misFirstRouterCtrl', ['$scope', '$itfreerHttp', '$formObject', '$itfreer_form_core','$state','$wdp',
		function($scope,$itfreerHttp, $formObject, $itfreer_form_core,$state,$wdp){
			$(".zs-ibox .title i a").toggle(function(){
				$(this).removeClass("up").addClass("down").parent().parent().next().slideUp();
			},function(){
				$(this).removeClass("down").addClass("up").parent().parent().next().slideDown();	
			})
			var stateName = $state.current.name;
			//$("a[ui-sref='"+stateName+"']").addClass("selected");
			$formObject.isMIS = true;
			$itfreer_form_core.destroyForm();
			$itfreer_form_core.destroyEasyui();
			$scope.stateObj = $state.current;
		}
	]);

	/**
	 * 表单最后一个控制器
	 */
	itfreerformcoreModule.controller('misLastRouterCtrl', ['$scope', '$itfreerHttp', '$formObject', '$itfreer_form_core',
		function($stateParams,$scope, $itfreerHttp, $formObject, $itfreer_form_core){
			$formObject.isMIS = true;
			$scope.materialShow=getWaterType();
			if(!$formObject.tempObject || !$formObject.tempObject.openFormKey){
				return;
			}

			var openFormKey = $formObject.tempObject.openFormKey;
			if(openFormKey=="openForm"){
				$itfreer_form_core.setEditRow($formObject.tempObject.formName, $formObject.tempObject.data);
			} else if(openFormKey=="openFormByKey"){
				 $itfreerHttp.getEntityByKey($formObject.tempObject.tableName, $formObject.tempObject.formDataKey,
					function(data){
						$scope.$apply(function() {
							if($formObject.tempObject.defaultValueFun){
								data = $formObject.tempObject.defaultValueFun(data);
							}
							$itfreer_form_core.setEditRow($formObject.tempObject.formName, data);
						});
					}, 
					function(xhr){ }
				);
			}
			$formObject.tempObject.openFormKey = "";
		}
	]);

	/**
	 * combotree控件
	 */
	itfreerformcoreModule.directive('agCombotree', function($http, $itfreerHttp, $itfreer_core, $formObject, $rootScope) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			template : '<select ></select>',
			scope : {
				data : "=",
				textValue : "@",
				unitValue : "@",
				selectedRow : "@",
				onlySelectLeaf : "@",
				click:"&ngClick"
			},
			link : function(scope, element, attrs, ctrl) {
				var bindValue = null;
				var order = {};
				order[attrs.order] = 1;
				var queryObject = attrs.queryObject || '';
				var pId = attrs.pId || '';
				var domainName = attrs.domainName || '';
				var jbs = attrs.jbs || '';
				var delay = attrs.delay === "true" ? true :false;
				var isLoaded = false;
				var jbField = attrs.jbfield || '';
				var allLoadJB = attrs.allloadjb || -1;
				
				var onlySelectLeaf = attrs.onlyselectleaf == "true" ? true : false;
				var multiple = attrs.multiple === "true" ? true : false;
				var options = {
					data : scope.data,
					disabled:attrs.disabled == "true"?true:false,
					multiple : multiple
				};
				
				scope.uiclick = function(){
					if($scope.click()){
		    			$scope.click()();
		    		}
				}
				
				if (multiple == true) {
					options.onCheck = function (node,checked) {
						var values = element.combotree('getValues');
						if (values) {
							if (values.length < 2) {
								//如果多选值只有一个或者没有，将数组改为字符串
								values = values[0] || '';
							}
							//转换为字符串
							values = values.join();
						};
						safeApply(scope,function() {
							ctrl.$setViewValue(values);
						});
					};
				}else{
					options.onSelect = function(record) {
						safeApply(scope,function() {
							ctrl.$setViewValue(record.id);
							
							var binder = $itfreer_core.getBinder(scope, scope.textValue);
							if (binder != null) {
								var text = record ? record.text : "";
								binder.obj[binder.field] = text;
							}
							
							binder = $itfreer_core.getBinder(scope, scope.unitValue);
							if (binder != null) {
								if(record && record.attributes && record.attributes.S_UNIT){
									binder.obj[binder.field] = record.attributes.S_UNIT;
								}else{
									binder.obj[binder.field] = "";
								}
							}
							
							binder = $itfreer_core.getBinder(scope, scope.selectedRow);
							if (binder != null) {
								binder.obj[binder.field] = record;
							}
						});
					};
					if(onlySelectLeaf){
						options.onBeforeSelect = function(record){
							var tree = $(this).tree;
							var isLeaf = tree('isLeaf', record.target);
							if(!isLeaf)
							{
								//$.messager.show({
								//	msg: '请选择叶子节点！'
								//});
								// 返回false表示取消本次选择操作
								return false;
							}
						}
					}
				}
				options['onBeforeExpand'] = function(row) {
					var id = row[attrs.idField];
					var pTree = element.combotree('tree');
					var nodes = [];
					try {
						nodes = pTree.tree('getChildren', row.target);
					} catch (e) {
					}
					var currtJB = row[jbField];
					if(allLoadJB == currtJB){
						return;
					}
					if (nodes == null || nodes.length <= 0) {
						$itfreerHttp.getTreeData(attrs.tableName, {}, order, id, '',domainName, -1,
								-1, true, function(treedata) {
									if (treedata == null || treedata.length <= 0) {
										// 最后一个节点
										row.state = 'open';
									} else {
										pTree.tree('append', {
											parent : row.target,
											data : treedata
										});
										pTree.tree('collapse', row.target);
										pTree.tree('expand', row.target);
									}
								}, function(ex) {
								});
					}
					return true;
				};

				options.onShowPanel = function () {
					if (!isLoaded && delay ==true && !attrs.parentField) {
						loadData();
					};
				};

				options.onLoadSuccess = function (data) {
					if(bindValue){
						element.combotree('setValue',bindValue);
					}else{
						element.combotree('setValue','');
						safeApply(scope,function() {
							ctrl.$setViewValue('');
						});
					}
					isLoaded = true;
				}
				
				var cm = element.combotree(options);

				$formObject.combotrees.push(cm);

				ctrl.$render = function() {
					var viewValue = ctrl.$viewValue ? ctrl.$viewValue : '';
					bindValue = viewValue;
					var opt = "setValue";
					if (multiple == true && viewValue.indexOf(',') != -1) {
						opt = "setValues";
						viewValue = viewValue.split(",");
					};
					element.combotree(opt, viewValue);
					if (!isLoaded && delay ==true && !attrs.parentField && ctrl.$viewValue) {
						loadData(function() {
							scope.$apply(function() {
								element.combotree(opt, viewValue);
							});
						});
					}else{
						element.combotree(opt, viewValue);
					}
				};

				if (attrs.dynamic == "true" && !attrs.parentField && delay != true) {
					loadData();
				}
				function loadData (afterDataLoaded) {
					$itfreerHttp.getTreeData(attrs.tableName, queryObject, order, pId, jbs,domainName,
						-1, -1, true, function(treedata) {
						element.combotree('loadData', treedata);
						if (afterDataLoaded && typeof afterDataLoaded ==="function") {
							afterDataLoaded();
						};
					}, function(ex) {
					});
				}
				//解决$digest already in progress
				function safeApply($scope, fn) {
				    ($scope.$$phase || $scope.$root.$$phase) ? fn() : $rootScope.$apply(fn);
				}
			}
		};
	});

	/**
	 * combotree控制器
	 */
	var agComboboxController = ['$scope','$attrs','$element','$itfreerHttp','$parse',
		function ($scope, $attr, $element, $itfreerHttp, $parse) {

		this.parentIdValue = null;
		this.parentCombo = null;

		if ($attr.parentCombo && $("#"+$attr.parentCombo)[0]) {
			this.parentCombo = $("#"+$attr.parentCombo);
			$scope[$attr.parentCombo] = $("#"+$attr.parentCombo);
		}
		var ctrl = this;
		var getIdValue = function () {
			var value = null;
			if (ctrl.parentCombo) {
				var parentData = ctrl.parentCombo.combobox('getData');
				var pValue = ctrl.parentCombo.combobox('getValue');
				var pIDField = ctrl.parentCombo.attr('id-Field');
				for (var i = 0; i < parentData.length; i++) {
					var record = parentData[i];
					if (pValue === record.id) {
						value = pIDField ? 
	 						(record[pIDField] ? record[pIDField] : record.attributes[pIDField]) : record.id;
	 					break;
					};
				};
			}
			return value;
		};
		//console.log(ctrl.parentCombo);
		if (!ctrl.parentCombo) {return;};
		$scope.$watch(function parentValueWatch(val) {
			var idValue = getIdValue();
			if (idValue !== ctrl.parentIdValue) {
				ctrl.parentIdValue = idValue;
				var filter = {};
				filter[$attr.parentField] = ctrl.parentIdValue || "-10000";
				$itfreerHttp.getDomains($attr.tableName, $attr.domainName,filter,$attr.addPinYin, function(data) {
					data = data ? data : [];
					if($attr.addspace){
							data.unshift({'id':'nullItem','text':'<空>'});
						}
					$element.combobox('loadData', data);
					var value = $element.combobox('getValue');
					var isExsit = false;
					for (var i = 0; i < data.length; i++) {
						if(data[i].id == value){
							isExsit = true;
							break;
						}
					};
					if (isExsit) {
						$element.combobox('clear');
						$element.combobox('select',value);
					}else{ 
						$element.combobox('select','');
						$element.combobox('clear'); 
					}
				}, function(ex) {
				});
			};
		});
	}];

	/**
	 * Combobox控件
	 */
	itfreerformcoreModule.directive('agCombobox', function($http, $itfreerHttp, 
			$parse, $itfreer_core, $formObject, $rootScope) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			template : '<select class="fore-common-select"></select>',
			scope : {
				data : "=",
				parentCombo : "@",
				textValue : "@",
				change :"&ngChange"
			},
			controller : agComboboxController,
			link : function(scope, element, attrs, ctrl) {
				var isLoaded = false;
				var multiple = attrs.multiple === "true" ? true : false;
				var options = {
					data : scope.data,
					valueField : 'id',
					textField : 'text',
					multiple : multiple,
					editable:false
				};
				options.onSelect = function(record) {
					var viewValue = record ? record.id : '';
					var text = record ? record.text : '';
					if (multiple == true && record) {
						viewValue = getEleValues();
					};
					if (record && record.id == "nullItem") {
						//如果选择为空值，不论多选还是单选，viewValue都为空
						viewValue = '';
						element.combobox('setValue', viewValue);
					};
					var binder = $itfreer_core.getBinder(scope, scope.textValue);
					if (binder != null) {
						binder.obj[binder.field] = text;
					}
					if(scope.change()){
						scope.change()(record);
					}
					scope.$apply(function() {
						ctrl.$setViewValue(viewValue);
					});
				};
				options.onUnselect = function(record) {
					if (multiple == true && record) {
						var viewValue = getEleValues();
						scope.$apply(function() {
							ctrl.$setViewValue(viewValue);
						});
					};
				};
				//获取下拉多选值
				function getEleValues () {
					var values = element.combobox('getValues');
					if (values) {
						if (values.length < 2) {
							//如果多选值只有一个或者没有，将数组改为字符串
							values = values[0] || '';
						}else{
							//当选择多个时去除选择中的空值
							for (var i = 0; i < values.length; i++) {
								if(values[i] == ''){
									values.remove(values[i]);
								}
							};
							//转换为字符串
							values = values.join();
						}
					};
					return values;
				}
				options.onShowPanel = function () {
					if (!isLoaded && attrs.delay =="true" && !attrs.parentField) {
						loadData();
					};
				};
				//数据加载成功时，触发此事件
				options.onLoadSuccess = function (data) {
					isLoaded = true;
					selectFirstRow();
					selectFirstRowBindBombobx();
					//解决$digest already in progress
					function safeApply($scope, fn) {
					    ($scope.$$phase || $scope.$root.$$phase) ? fn() : $rootScope.$apply(fn);
					}
					//默认选中第一行
					function selectFirstRow(){
						if(attrs.selectfirstrow){
							if(data && data[0]){
								
								safeApply(scope,function() {
									element.combobox('setValue', data[0]["id"]);
									ctrl.$setViewValue(data[0]["id"]);
								});
								
							}
						}
					}
					/**
					 * 如果是带有级联的，那么在父级控件上若果是默认选中第一行，child控件结果只有一条（县级用户）的时候才会默认
					 */
					function selectFirstRowBindBombobx(){
						if(attrs.parentCombo && scope[attrs.parentCombo] && scope[attrs.parentCombo].attr("selectFirstRow")){
							scope.$apply(function(){
								if(data &&  data["length"] == 1){
									element.combobox('setValue', data[0]["id"]);
									ctrl.$setViewValue(data[0]["id"]);
								}
							});
						}
					}
				};
				var cm = element.combobox(options);
				$formObject.comboboxs.push(cm);

				ctrl.$render = function() {
					var viewValue = ctrl.$viewValue ? ctrl.$viewValue : '';
					var opt = "setValue";
					if (multiple == true && viewValue.indexOf(',') != -1) {
						opt = "setValues";
						viewValue = viewValue.split(",");
					};
					if (!isLoaded && attrs.delay =="true" && !attrs.parentField && ctrl.$viewValue) {
						loadData(function() {
							scope.$apply(function() {
								element.combobox(opt, viewValue);
							});
						});
					}else{
						element.combobox(opt, viewValue);
						//viewValue 为 ''  说明是新增或者清空当前选项
						if(attrs.selectfirstrow && !viewValue){
							loadData();
						}
					}
				};
				//初始化动态加载下拉数据
				if (attrs.dynamic == "true" && !attrs.parentField && attrs.delay !="true") {
					loadData();
				}
				//加载下拉数据
				function loadData (afterDataLoaded) {
					var addSpaceItem = attrs.addspace == "true";
					var filter = attrs.initFilter ? attrs.initFilter : null;
					$itfreerHttp.getDomains(attrs.tableName, attrs.domainName,filter,attrs.addPinYin, function(
							data) {
						data = data ? data : [];
						if(addSpaceItem){
							data.unshift({'id':'nullItem','text':'<空>'});
						}
						element.combobox('loadData', data);
						if (afterDataLoaded && typeof afterDataLoaded ==="function") {
							afterDataLoaded();
						};
					}, function(ex) {
					});
				};
				
//				scope.$watch(scope.data,function(){
//					alert("改变啦");
//				});
				
				if (attrs.defvalue != null && ctrl.$viewValue == null) {
					if(attrs.defvalue=="{userid}"){
						var userID = $itfreer_core.getCookie("userid");
						element.combobox('setValue', userID);
					} else {
						element.combobox('setValue', attrs.defvalue);
					}
				}
			}
		};
	});
	/**
	 * Treegrid控件
	 */
	itfreerformcoreModule.directive('agTreegrid', function($http, $itfreerHttp, $formObject) {
		return {
			replace : true,
			restrict : 'E',
			template : '<table></table>',
			scope : {
				queryObject : "@",
				filterValue : "@"
			},
			link : function(scope, element, attrs, ctrl) {
				var options = {};
				options.columns = [];
				var obj = eval(attrs.columns);
				var checkboxFormatter = function(value,rowData,rowIndex){
					var cboxId = attrs.id + "_"+ rowData[attrs.idField];
					return "<input type='checkbox' name='" + attrs.id + "' id='" + cboxId + "'></input> " + value;
				};
				
				obj.forEach(function(item){
					if(item.hasOwnProperty("showCheckbox")
							&& item["showCheckbox"]==true
							&& !item.hasOwnProperty("formatter"))
					item.formatter = checkboxFormatter;
				});
				
				options.columns.push(obj);
				options.idField = attrs.idField;
				options.treeField = attrs.treeField;
				if (attrs.dynamic == "false" && attrs.formname) {
					options['onSelect'] = function(row) {
						scope.$apply(function() {
							scope.setEditRow(attrs.formname, row);
						});
					};
				}
				options['onBeforeExpand'] = function(row) {
					var id = row[attrs.idField];
					var nodes = element.treegrid('getChildren', id);
					if (nodes == null || nodes.length <= 0) {
						if(attrs.formname){
							$itfreerHttp.getTreeData(scope.formObject[attrs.formname].tableName, scope.formObject[attrs.formname].queryObject,
									scope.formObject[attrs.formname].orderObject, id, scope.formObject[attrs.formname].treeLoadJBs,'', 
									scope.formObject[attrs.formname].pageSize, scope.formObject[attrs.formname].pageIndex, false,
									function(treedata) {
										if (treedata == null || treedata.length <= 0) {
											// 最后一个节点
											row.state = 'open';
											element.treegrid('refresh', id);
											// 同步更新数据库
											row[scope.treeIsChildField] = "1";
											$itfreerHttp.save(scope.tableName, row, function(
													data) {
											}, function(ex) {
											});
										} else {
											element.treegrid('append', {
												parent : id,
												data : treedata
											});
											element.treegrid('refresh', id);
											element.treegrid('expand', id);
										}
									}, function(ex) {
							});
						}
					}
					return true;
				};
				var tg = element.treegrid(options);
				$formObject.treegrids.push(tg);

				if (attrs.dynamic == "true") {
					var tableName = attrs.tableName;

					var orderObjectEx = {};
					var msgs = attrs.orderObject.split(":");
					if(msgs.length==2){
						orderObjectEx[msgs[0]] = msgs[1];
					}else{
						orderObjectEx[orderField] = 0;
					}
					
					var queryObj = {};
					if(scope.queryObject){
						queryObj = scope.queryObject;
					}
					
					$itfreerHttp.getTreeData(tableName, queryObj, orderObjectEx, '', '','',
						scope.pageSize, scope.pageIndex, false, function(data) {
							element.treegrid('loadData', data);
						}, function(ex) {

					});
				}
				
//				scope.$watch(scope.queryObject,function(newVal){
//					var tableName = attrs.tableName;
//
//					var orderObjectEx = {};
//					var msgs = attrs.orderObject.split(":");
//					if(msgs.length==2){
//						orderObjectEx[msgs[0]] = msgs[1];
//					}else{
//						orderObjectEx[orderField] = 0;
//					}
//					
//					$itfreerHttp.getTreeData(tableName, scope.queryObject, orderObjectEx, '', '','',
//						scope.pageSize, scope.pageIndex, false, function(data) {
//							element.treegrid('loadData', data);
//						}, function(ex) {
//
//					});
//				});
				
				// element.treegrid('reload');
			}
		};
	});

	/**
	 * Datebox控件
	 */
	itfreerformcoreModule.directive('agDatebox', function($http, $itfreerHttp, $formObject, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			template : "<input></input>",
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var showCurDay = attrs.showCurday;
				var addDays=attrs.addDays;
				var options = {
					formatter : $itfreer_core.formatDate,
					editable : false
				};
				options['onSelect'] = function(date) {
					scope.$apply(function() {
						ctrl.$setViewValue($itfreer_core.formatDate(date));
					});
				};
				var db = element.datebox(options);
				$formObject.dateboxs.push(db);

				ctrl.$render = function() {
					if(typeof(ctrl.$viewValue) == "undefined" && showCurDay == "true"){
						var date = new Date();
						if(addDays!=null && addDays!="undefined" && addDays!=""){
							var day=date.getDate();
							var dayTime="";
							dayTime=Number(day)+Number(addDays);
							date.setDate(dayTime);
						}
			       		element.datebox('setValue', $itfreer_core.formatDate(date));
			       		ctrl.$setViewValue($itfreer_core.formatDate(date));
					}else{
						element.datebox('setValue', $itfreer_core.getDateObject(ctrl.$viewValue));
					}
				};
			}
		};
	});
	/**
	 * Datetimebox控件
	 */
	itfreerformcoreModule.directive('agDatetimebox', function($http, $itfreerHttp, $formObject, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			template : "<input></input>",
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var showCurDay = attrs.showCurday;
				var addDays=attrs.addDays;
				var options = {
					// formatter : $itfreer_core.formatDate,
					editable : false,
					showSeconds:false
				};
				options['onSelect'] = function(date) {
					scope.$apply(function() {
						var time=element.datetimebox('spinner').spinner('getValue');
						var dt = date.getFullYear()+'-'+ (date.getMonth()+1) +'-'+date.getDate()+' '+ time;
						element.datetimebox('setText',dt);
						element.datetimebox('hidePanel');
						ctrl.$setViewValue(dt);
					});
				};

				var db = element.datetimebox(options);

				$formObject.datetimeboxs.push(db);

				ctrl.$render = function() {
					if(typeof(ctrl.$viewValue) == "undefined" && showCurDay == "true"){
						var date = new Date();
						if(addDays!=null && addDays!="undefined" && addDays!=""){
							var day=date.getDate();
							var dayTime="";
							dayTime=Number(day)+Number(addDays);
							date.setDate(dayTime);
						}
			       		element.datetimebox('setValue', $itfreer_core.formatDate(date));
			       		ctrl.$setViewValue($itfreer_core.formatDate(date));
					}else{
						element.datetimebox('setValue', $itfreer_core.getDateObject(ctrl.$viewValue));
					}
				};
			}
		};
	});

	/**
	 * Textarea控件
	 */
	itfreerformcoreModule.directive('agTextarea', function($http, $itfreerHttp) {
		var sessionId = $("#_sessionid").html();
		return {
			replace : true,
			restrict : 'E',
			template : "<textarea></textarea>",
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var name = attrs['name'];
				var elementName = "textarea[name='" + name + "']";
				var editor = null;
				KindEditor.ready(function(K) {
					editor = K.create(elementName, {
						uploadJson : getBasePath() + '/kindeditor/upload.do?sessionId='+sessionId,
						fileManagerJson : getBasePath() + '/kindeditor/fileManager.do?sessionId='+sessionId,
						allowFileManager : true,
						afterChange : function() {
							scope.$apply(function() {
								ctrl.$setViewValue(editor.html());
							});
						}
					});
				});

				ctrl.$render = function() {
				    if(!editor)
				      return;
					if (ctrl.$viewValue == null) {
						editor.html('');
					} else {
						editor.html(ctrl.$viewValue);
					}
				};
			}
		};
	});

	/**
	 * Upload控件
	 */
	itfreerformcoreModule.directive('agUpload', function($parse, $itfreerHttp,$compile) {
		var sessionId = $("#_sessionid").html();
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var maxSize = attrs.maxSize ? attrs.maxSize : "200";
				var btnLable = attrs.btnLable ? attrs.btnLable : "上传";
				var downloadUrl = getBasePath()+'/plupload/download.do';
				var isEnabled = attrs.isEnabled;
				//定义鼠标移动到列表时的css效果
				var mouseenterCss = {"display":"inline-block"};
				if( typeof(isEnabled) == 'undefined' || isEnabled == ''){
					mouseenterCss = {"display":"inline-block"};
				}else{
					scope.$watch(isEnabled,function(newVal){
						if(newVal){
							mouseenterCss = {"display":"inline-block"};
							$("[flag = '"+isEnabled+"']").show();
						}else{
							mouseenterCss = {"display":"none"};
							$("[flag = '"+isEnabled+"']").hide();
						}
					});
				}
					
				
				var uploadHtml ='';
				uploadHtml ='<div>'
					 + '<input type="button" flag="'+isEnabled+'"'
					 + ' class="zs-btn" value="'+btnLable+'"/>'
					 + '</div>';
				var filters = attrs.extensions ? [{title : "文档", extensions : attrs.extensions}]:[
							{title : "所有文档", extensions : "*"}
						];
				
				var html = '<div></div>'
					 + uploadHtml
					 +'<div class="zs-file-list"><ul></ul></div>';

				var el = document.createElement("div");
				// el.className = "fore-sys-file-upload";
				el.innerHTML = html;
				var _winEl = el.firstChild;
				var _listEl = el.lastChild.firstChild;
				var _btnEl = _winEl.nextSibling.lastChild;
				var _valueEl = el.lastChild.firstChild;
				// element.html(templateString);
				element.html(el);
				
				$(_btnEl).click(function(){
					$(_winEl).window('open');
				});
				//删除按钮效果
				$(_listEl).on("mouseenter","li",function(){
					$(this).find("i a").css(mouseenterCss);
				}).on("mouseleave","li",function(){
					$(this).find("i a").css( {"display":"inline-block"});
				}).on('click', 'li i a', function(){
					//绑定删除事件
					_onDelFile(this);
				});
				
				$(_winEl).window({   
					title:'上传文件',
					minimizable:false,
					collapsible:false,
					shadow:true,
					maximizable:false,
					closed:true,
					width:600,    
					height:400,
					modal:true,
					onOpen:init_uploader
					});
				
				var fileList = [];
				var errors = [];

				//初始化上传控件
				function init_uploader () {
					if ($("#uploader")[0]) {
						$("#uploader").remove();
					};
					$(_winEl).append('<div id="uploader"><p>您的浏览器未安装 Flash, '
					+'Gears, BrowserPlus 或者支持 HTML5。</p></div>');
					$("#uploader").pluploadQueue({
						// General settings
						runtimes : 'html5,flash,gears,browserplus,html4',
						url : getBasePath()+'/plupload/upload.do?sessionId='+sessionId,
						max_file_size : maxSize+'mb',
						unique_names : true,
						multiple_queues : true,
						chunk_size: '512kb',
						// Specify what files to browse for
						filters : filters,
						// Flash settings
						flash_swf_url : getJsBasePath()+'/style/script/plupload/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/style/script/plupload/Moxie.xap',
						/*flash_swf_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.xap',*/
						init:{
							FileUploaded:function(uploader,file,response){
								if(response.response){
									var rs = $.parseJSON(response.response);
									if(rs.status){
										var fileInfo = rs.newName + ":" + file.name;
										_addFileListItem(fileInfo);
										var onUploadFn = null;
										if(attrs.hasOwnProperty("onUploaded") && attrs.onUploaded && attrs.onUploaded!=""){
											onUploadFn = $parse(attrs.onUploaded);
										}
										if(onUploadFn){
											scope.$apply(function() {
												onUploadFn(scope,{file:fileInfo});	
											});
										}
									}else{
										errors.push(file.name);
									}
								}
							},
							UploadComplete:function(uploader,fs){
								uploader.splice();//从上传队列中删除所有文件
								uploader.refresh();
								uploader.destroy();//ie9以下若不销毁此对象第二次上传会十分缓慢
								$("#uploader").remove();
								$(_winEl).window('close');
							}
						}
					});
				}

				//添加到文件列表
				function _addFileListItem (fileInfo) {
					if (!fileInfo) return;
					fileInfoArr = fileInfo.split(":");
					var url = fileInfoArr[0];
					var name = fileInfoArr[1];
					fileList.push(fileInfo);
					var _index = fileList.indexOf(fileInfo);
					var xel ='';
					xel = '<i><a docIndex="'+_index+'" ></a></i>';
					var _downloadUrl = downloadUrl+"?filePath="+url.replace(getBasePath()+"/","")+"&fileName="+encodeURIComponent(name);
					//1024分辨率下控制文件的名字长度为 14 个中文字符的长度，超过后以...显示名称
					var $fileLi = $('<li><a href="'+_downloadUrl+'" title="'+name+'">'+name+'</a>'+xel+'</li>').appendTo($(_listEl));
					//{{}}有时会出现错乱的问题，页面输出{{name}}
					//var $fileLi = $('<li><a href="'+_downloadUrl+'" title="'+name+'">{{"'+name+'" | asLength:20}}</a>'+xel+'</li>').appendTo($(_listEl));
					$fileLi = $compile($fileLi)(scope);
					_rebuildValue();
				}
				//重新赋值
				function _rebuildValue () {
					var fileString = fileList.join("|");
					$(_valueEl).val(fileString);
					if(!scope.$$phase){
						scope.$apply(function () {
							ctrl.$setViewValue(fileString);
						});
					}
				}

				function _onDelFile (target) {
					$.messager.confirm('确认操作', '确定要删除这个文件吗？', function(action){
						if (action){
						    var $fileLi = $(target).closest('li').hide();
							var docIndex = $(target).attr('docIndex');
							$fileLi.remove();
							//从列表中删除
							fileList.splice(docIndex,1);
							_rebuildValue();
						}
					});
				}
				
				ctrl.$render = function() {
					//删除文件列表
					fileList = [];
					$(_listEl).empty();
					if (!ctrl.$viewValue) {
						$(_valueEl).val("");
					} else {
						var fileInfo = ctrl.$viewValue.split("|");
						for (var i = 0; i < fileInfo.length; i++) {
							_addFileListItem(fileInfo[i]);
						};
					}
				};
			}
		};
	});

	/**
	 * Upload1控件
	 */
	itfreerformcoreModule.directive('agUpload1', function($parse, $itfreerHttp,$compile) {
		var sessionId = $("#_sessionid").html();
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var maxSize = attrs.maxSize ? attrs.maxSize : "200";
				var btnLable = attrs.btnLable ? attrs.btnLable : "上传";
				var downloadUrl = getBasePath()+'/plupload/download.do?sessionId='+sessionId;
				var isEnabled = attrs.isEnabled;
				//定义鼠标移动到列表时的css效果
				var mouseenterCss = {"display":"inline-block"};
				if( typeof(isEnabled) == 'undefined' || isEnabled == ''){
					mouseenterCss = {"display":"inline-block"};
				}else{
					scope.$watch(isEnabled,function(newVal){
						if(newVal){
							mouseenterCss = {"display":"inline-block"};
							$("[flag = '"+isEnabled+"']").show();
						}else{
							mouseenterCss = {"display":"none"};
							$("[flag = '"+isEnabled+"']").hide();
						}
					});
				}
				
				
				var uploadHtml ='';
				uploadHtml ='<div style="float:right">'
					+ '<a style="cursor: pointer;text-decoration:underline;color:blue;" flag="'+isEnabled+'">'+btnLable+'</a>'
					+ '</div>';
				var filters = attrs.extensions ? [{title : "文档", extensions : attrs.extensions}]:[
				                                                                                  {title : "所有文档", extensions : "*"}
				                                                                                  ];
				
				var html = '<div></div>'
					+ uploadHtml
					+'<div style="float:left" class="zs-file-list"><ul></ul></div>';
				
				var el = document.createElement("div");
				// el.className = "fore-sys-file-upload";
				el.innerHTML = html;
				var _winEl = el.firstChild;
				var _listDiv = el.lastChild;
				var _listEl = el.lastChild.firstChild;
				var _btnEl = _winEl.nextSibling.lastChild;
				var _valueEl = el.lastChild.firstChild;
				// element.html(templateString);
				element.html(el);
				
				$(_btnEl).click(function(){
					$(_winEl).window('open');
				});
				//删除按钮效果
				$(_listEl).on("mouseenter","li",function(){
					$(this).find("i a").css(mouseenterCss);
				}).on("mouseleave","li",function(){
					$(this).find("i a").css( {"display":"none"});
				}).on('click', 'li i a', function(){
					//绑定删除事件
					_onDelFile(this);
				});
				
				$(_winEl).window({   
					title:'上传文件',
					minimizable:false,
					collapsible:false,
					shadow:true,
					maximizable:false,
					closed:true,
					width:600,    
					height:400,
					modal:true,
					onOpen:init_uploader
				});
				
				var fileList = [];
				var errors = [];
				
				//初始化上传控件
				function init_uploader () {
					if ($("#uploader")[0]) {
						$("#uploader").remove();
					};
					$(_winEl).append('<div id="uploader"><p>您的浏览器未安装 Flash, '
							+'Gears, BrowserPlus 或者支持 HTML5。</p></div>');
					$("#uploader").pluploadQueue({
						// General settings
						runtimes : 'gears,flash,browserplus,html5,html4',
						url : getBasePath()+'/plupload/upload.do?sessionId='+sessionId,
						max_file_size : maxSize+'mb',
						unique_names : true,
						multiple_queues : true,
						chunk_size: '512kb',
						// Specify what files to browse for
						filters : filters,
						// Flash settings
						flash_swf_url : getJsBasePath()+'/style/script/plupload/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/style/script/plupload/Moxie.xap',
						/*flash_swf_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.xap',*/
						init:{
							FileUploaded:function(uploader,file,response){
								if(response.response){
									var rs = $.parseJSON(response.response);
									if(rs.status){
										var fileInfo = rs.newName + ":" + file.name;
										_addFileListItem(fileInfo);
										var onUploadFn = null;
										if(attrs.hasOwnProperty("onUploaded") && attrs.onUploaded && attrs.onUploaded!=""){
											onUploadFn = $parse(attrs.onUploaded);
										}
										if(onUploadFn){
											scope.$apply(function() {
												onUploadFn(scope,{file:fileInfo});	
											});
										}
									}else{
										errors.push(file.name);
									}
								}
							},
							UploadComplete:function(uploader,fs){
								uploader.splice();//从上传队列中删除所有文件
								uploader.refresh();
								uploader.destroy();//ie9以下若不销毁此对象第二次上传会十分缓慢
								$("#uploader").remove();
								$(_winEl).window('close');
							}
						}
					});
				}
				
				//添加到文件列表
				function _addFileListItem (fileInfo) {
					if (!fileInfo) return;
					fileInfoArr = fileInfo.split(":");
					var url = fileInfoArr[0];
					var name = fileInfoArr[1];
					fileList.push(fileInfo);
					var _index = fileList.indexOf(fileInfo);
					var xel ='';
					xel = '<i><a docIndex="'+_index+'" ></a></i>';
					var _downloadUrl = downloadUrl+"?filePath="+url.replace(getBasePath()+"/","")+"&fileName="+encodeURIComponent(name);
					if($(_listDiv).find("label"))
						$(_listDiv).find("label").remove();
					
					//1024分辨率下控制文件的名字长度为 14 个中文字符的长度，超过后以...显示名称
					var $fileLi = $('<li><a href="'+_downloadUrl+'" title="'+name+'">{{"'+name+'" | asLength:20}}</a>'+xel+'</li>').appendTo($(_listEl));
					$fileLi = $compile($fileLi)(scope);
					_rebuildValue();
				}
				//重新赋值
				function _rebuildValue () {
					var fileString = fileList.join("|");
					$(_valueEl).val(fileString);
					if(!scope.$$phase){
						scope.$apply(function () {
							ctrl.$setViewValue(fileString);
						});
					}
				}
				
				function _onDelFile (target) {
					$.messager.confirm('确认操作', '确定要删除这个文件吗？', function(action){
						if (action){
							var $fileLi = $(target).closest('li').hide();
							var docIndex = $(target).attr('docIndex');
							$fileLi.remove();
							//从列表中删除
							fileList.splice(docIndex,1);
							if(fileList.length==0  && $(_listDiv).find("label").length==0){
								$("<label>无</label>").appendTo($(_listDiv));
							}
							_rebuildValue();
						}
					});
				}
				
				ctrl.$render = function() {
					//删除文件列表
					fileList = [];
					$(_listEl).empty();
					if (!ctrl.$viewValue) {
						$(_valueEl).val("");
						if(fileList.length==0 && $(_listDiv).find("label").length==0){
							$("<label>无</label>").appendTo($(_listDiv));
						}
					} else {
						if($(_listDiv).find("label"))
							$(_listDiv).find("label").remove();
						var fileInfo = ctrl.$viewValue.split("|");
						for (var i = 0; i < fileInfo.length; i++) {
							_addFileListItem(fileInfo[i]);
						};
					}
				};
			}
		};
	});
	/**
	 * Upload Image控件
	 */
	itfreerformcoreModule.directive('agUploadImage', function($parse, $itfreerHttp,$compile) {
		var sessionId = $("#_sessionid").html();
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var maxSize = attrs.maxSize ? attrs.maxSize : "200";
				var btnLable = attrs.btnLable ? attrs.btnLable : "上传";
				var delLable = attrs.delLable ? attrs.delLable : "删除";
				var noImage = attrs.noImage ? attrs.noImage : "";
				var isEnabled = attrs.isEnabled;
				var downloadUrl = getBasePath()+'/plupload/download.do?sessionId='+sessionId;
				//定义鼠标移动到列表时的css效果
				var mouseenterCss = {"display":"inline-block"};
				if( typeof(isEnabled) == 'undefined' || isEnabled == ''){
					mouseenterCss = {"display":"inline-block"};
				}else{
					scope.$watch(isEnabled,function(newVal){
						if(newVal){
							mouseenterCss = {"display":"inline-block"};
							$("[flag = '"+isEnabled+"']").show();
						}else{
							mouseenterCss = {"display":"none"};
							$("[flag = '"+isEnabled+"']").hide();
						}
					});
				}
				
				var uploadHtml ='';
				uploadHtml ='<div style="float: middle" flag="'+isEnabled+'">'
					+ '<a style="cursor: pointer;text-decoration:underline;color:blue;" flag="'+isEnabled+'">'+btnLable+'</a>'
					+ '&nbsp;&nbsp;<a style="cursor: pointer;text-decoration:underline;color:blue;" flag="'+isEnabled+'">'+delLable+'</a>'
					+ '</div>';
				var filters =  [{title : "图片", extensions : "jpg,png"}];
				
				var html = '<div></div>'
					+'<div><img onclick="imgShow($(this))" width="100px" height="100px" src="'+noImage+'"/></div>'
					+ uploadHtml;
				
				var el = document.createElement("div");
				el.innerHTML = html;
				var _winEl = el.firstChild;
				var _btnEl = el.lastChild.firstChild;
				var _delEl = el.lastChild.lastChild;
				var _imageEl = _winEl.nextSibling.lastChild;
				
				element.html(el);
				
				$(_btnEl).click(function(){
					$(_winEl).window('open');
				});
				$(_delEl).click(function(){
					_delImageSrc(this);
				});
				
				$(_winEl).window({   
					title:'选择图片',
					minimizable:false,
					collapsible:false,
					shadow:true,
					maximizable:false,
					closed:true,
					width:600,    
					height:400,
					modal:true,
					onOpen:init_uploader
				});
				
				var fileList = [];
				var errors = [];
				
				//初始化上传控件
				function init_uploader () {
					if ($("#uploader")[0]) {
						$("#uploader").remove();
					};
					$(_winEl).append('<div id="uploader"><p>您的浏览器未安装 Flash, '
							+'Gears, BrowserPlus 或者支持 HTML5。</p></div>');
					$("#uploader").pluploadQueue({
						// General settings
						runtimes : 'gears,flash,browserplus,html5,html4',
						url : getBasePath()+'/plupload/upload.do?sessionId='+sessionId,
						max_file_size : maxSize+'mb',
						unique_names : true,
						multiple_queues : true,
						chunk_size: '512kb',
						// Specify what files to browse for
						filters : filters,
						// Flash settings
						flash_swf_url : getJsBasePath()+'/style/script/plupload/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/style/script/plupload/Moxie.xap',
						/*flash_swf_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.xap',*/
						init:{
							FileUploaded:function(uploader,file,response){
								if(response.response){
									var rs = $.parseJSON(response.response);
									if(rs.status){
										var fileInfo = rs.newName;
										_updateImageSrc(fileInfo);
									}else{
										errors.push(file.name);
									}
								}
							},
							UploadComplete:function(uploader,fs){
								uploader.splice();//从上传队列中删除所有文件
								uploader.refresh();
								uploader.destroy();//ie9以下若不销毁此对象第二次上传会十分缓慢
								$("#uploader").remove();
								$(_winEl).window('close');
							}
						}
					});
				}
				
				//更新Image Src
				function _updateImageSrc (fileInfo) {
					if (!fileInfo) return;
					var newFileInfo = fileInfo.split(":")[0];
					
					var _downloadUrl = "../"+newFileInfo.replace(getBasePath()+"/","");
					$(_imageEl).attr("src",_downloadUrl);//+Math.random()
					
					if(!scope.$$phase){
						scope.$apply(function () {
							ctrl.$setViewValue(fileInfo);
						});
					}
				}
				
				//删除图片
				function _delImageSrc (target) {
					$.messager.confirm('确认操作', '确定要删除图片吗？', function(action){
						if (action){
							$(_imageEl).attr("src",noImage);
							
							if(!scope.$$phase){
								scope.$apply(function () {
									ctrl.$setViewValue("");
								});
							}
						}
					});
				}
				
				ctrl.$render = function() {
					if (!ctrl.$viewValue) {
						$(_imageEl).attr("src",noImage);
					} else {
						var fileInfo = ctrl.$viewValue;
						_updateImageSrc(fileInfo);
					}
				};
			}
		};
	});
	/**
	 * 控件隐藏时验证不可用
	 */
	itfreerformcoreModule.directive('hideNovalidate', function($http, $itfreerHttp) {
		var sessionId = $("#_sessionid").html();
		return {
			require: ['ngModel','^form'],
			restrict : 'A',
			link : function(scope, element, attrs,ctrls) {
				var modelCtrl = ctrls[0];
				var formCtrl = ctrls[1];
				if (!formCtrl) return;

				scope.$watch(function getDisplay() {
					return scope.$eval(attrs.hideNovalidate);
				},function ngShowWatch(val) {
			        if (!val) {
			        	//控件隐藏,从表单控制器中删除
						formCtrl.$removeControl(modelCtrl);
			        }else{
			        	//控件显示,添加到表单控制器,并根据控件验证状态修改表单表单验证状态
			        	formCtrl.$addControl(modelCtrl);
						angular.forEach(modelCtrl.$error, function(validity, validationKey) {
							formCtrl.$setValidity(validationKey, !validity, modelCtrl);
						});
			        }
				});
			}
		};
	});

	/**
	 * Excel导入
	 */
	itfreerformcoreModule.directive('agImpexcel', function($http, $parse, $itfreerHttp, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var btnclass = attrs.btnclass ? attrs.btnclass : "zs-btn";
				var html = "<div></div> " +
						"<input type='button' class='" +btnclass+"' value='"+attrs.btntext+"' />";

				var el = document.createElement("span");
				// el.className = "fore-sys-file-upload";
				el.innerHTML = html;
				var _winEl = el.firstChild;
				var _btnEl = el.lastChild;
				element.html(el);
				
				$(_btnEl).click(function(){
					$(_winEl).window('open');
				});

				$(_winEl).window({   
					title:'Excel导入',
					minimizable:false,
					collapsible:false,
					shadow:true,
					maximizable:false,
					closed:true,
					width:600,    
					height:310,
					modal:true,
					onOpen:init_uploader
					});
				
				var maxSize = attrs.maxSize ? attrs.maxSize : "200";
				var files = [];
				var errors = [];
				var fileObject = {};
				
				//初始化上传控件
				function init_uploader () {
					if ($("#uploaderExcel")[0]) {
						$("#uploaderExcel").remove();
					};
					$(_winEl).append('<div id="uploaderExcel"><p>您的浏览器未安装 Flash, ' +'Gears, BrowserPlus 或者支持 HTML5。</p></div>');
					$("#uploaderExcel").pluploadQueue({
						// General settings
						runtimes : 'gears,flash,browserplus,html5,html4',
						url : getBasePath()+'/excelplupload/upload.do?excelid='+attrs.excelid,
						max_file_size : maxSize+'mb',
						unique_names:true,
						unique_names : true,
						multiple_queues : true,
						chunk_size: '512kb',
						multi_selection: false,
						// Specify what files to browse for
						filters : [
							{title : "Excel", extensions : "xls,xlsx"}
						],
						// Flash settings
						flash_swf_url : getJsBasePath()+'/style/script/plupload/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/style/script/plupload/Moxie.xap',
						/*flash_swf_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.xap',*/
						init:{
							FileUploaded:function(uploader,file,response){
								if(response.response){
									var rs = $.parseJSON(response.response);
									if(rs.status){
										files.push(file.name);
										fileObject = rs.resultObject;
										
										var onUploadFn = null;
										if(attrs.hasOwnProperty("onUploaded") && attrs.onUploaded && attrs.onUploaded!=""){
											onUploadFn = $parse(attrs.onUploaded);
										}
										
										var binder = $itfreer_core.getBinder(scope, attrs.editrow);
										if(onUploadFn){
											if(binder!=null){
												scope.$apply(function() {
													onUploadFn(scope,{file:fileObject,editrow:binder.obj[binder.field]});	
												});
											}else{
												scope.$apply(function() {
													onUploadFn(scope,{file:fileObject});	
												});
											}
										}
									}
								}
							},
							UploadComplete:function(uploader,fs){
								uploader.splice();//从上传队列中删除所有文件
								uploader.refresh();
								uploader.destroy();//ie9以下若不销毁此对象第二次上传会十分缓慢
								$("#uploaderExcel").remove();
								$(_winEl).window('close');
							},
							FilesAdded: function (up, files) {
							    $.each(up.files, function (i, file) {
							        if (up.files.length <= 1) {
							            return;
							        }
							        up.removeFile(file);
							    });
							}
						}
					});
				}
			}
		};
	});

	/**
	 * 默认选择人
	 */
	itfreerformcoreModule.directive('agUser', function($http, $itfreerHttp, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			scope : {
				textValue : "@",
				canuse : "@"
			},
			link : function(scope, element, attrs, ctrl) {
				
				var labelId = "label_"+attrs.id;
				var templateString = "<label id='"+labelId+"'></label>";
				element.html(templateString);
				
				scope.$watch(function(){
					setUser();
				});
				
				ctrl.$render = function() {
					setUser();
				};
				
				function setUser() {
					if (typeof(ctrl.$viewValue) == "undefined" || ctrl.$viewValue == null || ctrl.$viewValue == "") {
						if(scope.canuse=='true'){
							var userid = $itfreer_core.getCookie("userid");
							var userrealname = decodeURI(escape($itfreer_core.getCookie("username")));
							ctrl.$setViewValue(userid);
							$('#'+labelId).text(userrealname);
						}else{
							$('#'+labelId).text("");
						}
					} else {
						if(ctrl.$viewValue == "-1"){
							$('#'+labelId).text("超级管理员");
						}else{
							var userName = "";
							var binder = $itfreer_core.getBinder(scope, scope.textValue);
							if (binder != null) {
								userName = binder.obj[binder.field];
								userName = userName ? userName : '';
							}
							if(userName=="-1"){
								$('#'+labelId).text("超级管理员");
							}else{
								if(userName!=""){
									$('#'+labelId).text(userName);
								}
							}
						}
					}
				};
			}
		};
	});

	/**
	 * 默认时间
	 */
	itfreerformcoreModule.directive('agDate', function($http, $itfreerHttp, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			scope : {
				canuse : "@"
			},
			link : function(scope, element, attrs, ctrl) {
				
				var labelId = "label_"+attrs.id;
				var templateString = "<label id='"+labelId+"'></label>";
				element.html(templateString);
				
				scope.$watch(function(){
					setDate();
				});
				
				ctrl.$render = function() {
					setDate();
				};
				
				function setDate() {
					if (typeof(ctrl.$viewValue) == "undefined" || ctrl.$viewValue == null || ctrl.$viewValue == "") {
						if(scope.canuse=='true'){
							var date = new Date();
							var fmDate = formatDate(date);
				       		ctrl.$setViewValue(fmDate);
							$('#'+labelId).text(fmDate);
						}else{
							$('#'+labelId).text("");
						}
					} else {
						var fmDate = $itfreer_core.getDateObject(ctrl.$viewValue);
						$('#'+labelId).text(fmDate);
					}
				};
			}
		};
	});

	/**
	 * 具有打印功能的按钮
	 */
	itfreerformcoreModule.directive('agPrintButton', function($itfreer_form_core, $sce) {
		return {
			restrict : 'EA',
			template : '<input type="button" class="fore-common-btn" value="{{label}}">',
			scope: { 
				label : '@',		//按钮上显示的文字
				method : '@', 		//打印方式 html|table|template
				targetId : '@', 	//目标元素的id（method为template时不可用）
				taskName : '@', 	//打印任务名
				pageSize : '@', 	//纸张规格 A4|B5
				pageDirection : '@', //纸张方向 1:竖向 | 2:横向
				padding : '@'		//页边距，单位毫米。可以是一个值代表四个边距，也可以是“上,右,左,下”，也可以是“两边,上下” 
			},
			link : function(scope, element, attrs) {
				//纸张大小，每种纸张规格数组代表竖向放置时的[宽, 高]
				var PAGESIZE = {
					A4 : [210, 297],
					B5 : [182, 257]
				};
				var lodop = $itfreer_form_core.getLodop(),
					method = scope.method || 'html',
					taskName = scope.taskName || '打印任务',
					pageSize = setPageSize(scope.pageSize || 'A4'),
					pageDirection = setPageDirection(scope.pageDirection),
					padding = setPadding(scope.padding || "25,20,22,20");
				function setPageSize(pageSize) {
					pageSize = pageSize.toUpperCase();
					if(PAGESIZE[pageSize]){
						return pageSize;
					}else{
						console.warn('agPrintButton页面规格设置不正确，将使用默认配置:A4');
						return 'A4';
					}
				};
				function setPageDirection(pageDirection){
					var r = 1;
					switch(pageDirection){
						case '1': r = 1; break;
						case '2': r = 2; break;
						default : break;
					}
					return r;
				};
				function setPadding(padding) {
					var paddings = padding.split(',');
					for(var i=0; i<paddings.length; i++){
						paddings[i] = parseInt(paddings[i]);
					}
					if(paddings.length===1){
						return [paddings[0],paddings[0],paddings[0],paddings[0]];
					}else if(paddings.length===2){
						return [paddings[1],paddings[0],paddings[1],paddings[0]];
					}else if(paddings.length===4){
						return paddings;
					}else{
						console.warn('agPrintButton页边距设置不正确，将使用默认配置：[25,20,22,20]');
						return [25,20,22,20];
					}
				};
				element.on('click', function(event) {
					if (!lodop) {
						var url = navigator.userAgent.indexOf('Win64') >= 0 ?
							$itfreer_form_core.urls.lodopPlugin64 : $itfreer_form_core.urls.lodopPlugin32;
						var ele = document.createElement('div');
						ele.id = "lodopDownWin";
						$(ele).appendTo('body');
						$(ele).window({
							title : '请安装打印控件',  
						    width:500,    
						    height:200,    
						    modal:true,
						    content:'<div style="width:400px;">'+
									'<p>您需要安装打印控件才能使用打印功能，请' + 
									'<a href="'+url+'" style="color:red">点击这里</a>下载打印控件并安装。</p>' + 
									'<p>安装成功后需<a href="'+location.href+'" style="color:red">刷新</a>页面。</p>' +
									'<p style="color:#777">提示：打印控件只需安装一次，支持IE（包括以IE为内核的各种国产浏览器）、'+
									'Chrome(33版本之前,后续chrome版本停止支持NPPlugin,打印控件暂不可用)、火狐、Safari以及Opera等各种主流浏览器。<br/>' +
									(navigator.userAgent.indexOf('Firefox') == -1 ? '' :
										'对于火狐浏览器，如曾安装过Lodop旧版附件npActiveXPLugin，请在【工具】->【附加组件】->【扩展】中先卸它。</p>') +
									'</div>'  
						});		
					}else{
						_previewPrint();
					}
				});
				function _previewPrint(){
					switch(method){
						case 'html' :
							_previewPrintHtml(false);
							break;
						case 'table' :
							_previewPrintHtml(true);
							break;
						case 'template' : 
							//TODO:模板方式打印
							break;
						default : 
							console.error('不支持的打印方式：'+method);
					}
				};
				function _previewPrintHtml(isTable){
					scope.$apply(function () {
						var target = document.getElementById(scope.targetId);
						var html = target ? target.outerHTML : '';
						lodop.PRINT_INIT(taskName);
						lodop.SET_PRINT_PAGESIZE (pageDirection, 0, 0, pageSize);
						var pageType = PAGESIZE[pageSize]
						var width = ((pageDirection==1 ? pageType[0] : pageType[1])- padding[1] - padding[3]) + 'mm';
						var height = ((pageDirection==1 ? pageType[1] : pageType[0])- padding[0] - padding[2]) + 'mm';
						var left = padding[3]+'mm';
						var top = padding[0]+'mm';
						if(isTable)
							lodop.ADD_PRINT_TABLE(top, left, width, height, html);
						else
							lodop.ADD_PRINT_HTM(top, left, width, height, html);
						lodop.PREVIEW();
					});
				}
			}
		};
	});

	/**
	 * 获取焦点
	 */
	itfreerformcoreModule.directive('agFocus', function($document) {
	    return function(scope, element, attrs) {
	        $(element).bind('focus', function(e){
	            scope.$apply(attrs.agFocus);
	        });
	    };
	});

	/**
	 * 获取焦点
	 */
	itfreerformcoreModule.directive('itfreerWindow', function($document, $formObject) {
	    return function(scope, element, attrs) {
	        var title = "编辑";
			if(attrs.title){
				title = attrs.title;
			}

			var width = 800;
			if(attrs.width){
				width = parseInt(attrs.width);
			}

			var height = 400;
			if(attrs.height){
				height = parseInt(attrs.height);
			}
			var destroy = function(){
				alert('aa');
			};
			
			//存在相同的id，先删除，再添加
			for(var i=0;i<$formObject.windows.length;i++){
				if($formObject.windows[i].attr('id')==element.attr('id')){
					$formObject.windows[i].window('destroy');
					$formObject.windows.splice(i,1);
					break;
				}
			}

			var pw = $(element).window({
				iconCls:'icon-edit',
				modal:true,
				closed:true,
				minimizable:false,
				collapsible:false,
				shadow:true,
				maximizable:false,
				resizable:false,
			    title: title,
			    width: width,
			    height: height
			});
			$formObject.windows.push(pw);
	    };
	});

	/**
	 * 下拉菜单
	 */
	itfreerformcoreModule.directive('itfreerSplitbutton', function($document) {
	    return function(scope, element, attrs) {
	        $(element).splitbutton({menu:'#'+attrs.mid});
	    };
	});

	// 异步加载指今
	itfreerformcoreModule.directive('agInclude', 
		['$http', '$templateCache', '$anchorScroll', '$animate', '$sce', 
		function($http,$templateCache,$anchorScroll,$animate,$sce) {
		    return {
			    restrict: 'ECA',
			    priority: 400,
			    terminal: true,
			    transclude: 'element',
			    controller: angular.noop,
			    compile: function(element, attr) {
			      	var srcExp = attr.ngInclude || attr.src,
			          	onloadExp = attr.onload || '',
			          	autoScrollExp = attr.autoscroll;

			      	return function(scope, $element, $attr, ctrl, $transclude) {
				        var changeCounter = 0,
				            currentScope,
				            previousElement,
				            currentElement;

			        	var cleanupLastIncludeContent = function() {
					        if(previousElement) {
					            previousElement.remove();
					            previousElement = null;
					        }
					        if(currentScope) {
					            currentScope.$destroy();
					            currentScope = null;
					        }
					        if(currentElement) {
					            $animate.leave(currentElement, function() {
					              previousElement = null;
					            });
					            previousElement = currentElement;
					            currentElement = null;
					        }
			        	};

				        scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
					        var afterAnimation = function() {
					            if (autoScrollExp && (!autoScrollExp || scope.$eval(autoScrollExp))) {
					              $anchorScroll();
					            }
					        };
					        var thisChangeId = ++changeCounter;
					        if (src) {
					            $http.get(src, {cache: $templateCache}).success(function(response) {
						            if (thisChangeId !== changeCounter) return;
						            var newScope = scope.$new();
						            ctrl.template = response;

						            var clone = $transclude(newScope, function(clone) {
						                cleanupLastIncludeContent();
						                $animate.enter(clone, null, $element, afterAnimation);
						            });

						            currentScope = newScope;
						            currentElement = clone;

						            currentScope.$emit('$includeContentLoaded');
						            scope.$eval(onloadExp);
					            }).error(function() {
					              	if (thisChangeId === changeCounter) cleanupLastIncludeContent();
					            });
					            scope.$emit('$includeContentRequested');
					        } else {
					            cleanupLastIncludeContent();
					            ctrl.template = null;
					        }
				        });
			      	};
			    }
			};
		}]
	);

	// 异步加载指今
	itfreerformcoreModule.directive('agInclude', 
		['$compile', '$sce', function($compile, $sce) {
		    return {
		      	restrict: 'ECA',
		      	priority: -400,
		      	require: 'agInclude',
		      	link: function(scope, $element, $attr, ctrl) {
		      		scope.totalCart = function() {
					    return $attr.show;
					};
		      		scope.$watch(scope.totalCart, function(){
						if($attr.show && $attr.show=='true'){
							if($element.context.innerText.length<=0){
								$element.html(ctrl.template);
			        			$compile($element.contents())(scope);
							}
			      		}
					});
		      	}
		    };
		}]
	);

	/**
	 * 附件显示
	 */
	itfreerformcoreModule.filter("asFiles", ['$sce', function ($sce) {
		return function (input) {
	    	var msgs = input.split("|");
	    	var result = "";
	    	msgs.forEach(function(item){
	    		var fileItems = item.split(":");
	    		result += "<a title='"+fileItems[1]+"' href='"+fileItems[0]+"'>"+fileItems[1]+"</a> ";
	    	});
	    	return $sce.trustAsHtml(result);
	    };
	}]);

	/* 
	 * 当前流程审批用户
	 */
	itfreerformcoreModule.filter("asBpmUsers", function () {
	    return function (input) {
	    	if(input==null || input==""){
	    		return "";
	    	}
	    	var tasks = input.split(":");
	    	if(tasks.length==1){
	    		var users = tasks[0].split(",");
	            var userReturn = "";
	            for(var i=2; i<users.length; i+=2){
	            	userReturn += users[i+1] + ",";
	            }
	            userReturn = userReturn.substring(0, userReturn.length-1);
	            return userReturn;
	    	} else {
	    		var userReturn = "";
	    		for(var j=0; j<tasks.length; j++){
	    			var users = tasks[j].split(",");
	    			userReturn += users[1] + "(";
	                for(var i=2; i<users.length; i+=2){
	                	userReturn += users[i+1] + ",";
	                }
	                userReturn = userReturn.substring(0, userReturn.length-1) + "),";
	            }
	    		userReturn = userReturn.substring(0, userReturn.length-1);
	            return userReturn;
	    	}
	    };
	});

	/* 
	 * 加载服务器
	 */
	itfreerformcoreModule.run(function($rootScope, $itfreerHttp, $itfreer_form_core, $formObject) {
	  	
	});
}(window, angular));
/**itfreer.form.gis.js**/
/**
 * 定义itfreer.form.gis模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义gis配置模块
	 */
	var itfreerformgisModule = angular.module('itfreer.form.gis', ['itfreer.form.core']);

	/**
	 * 定义gis配置模块服务
	 */
	itfreerformgisModule.factory('$itfreer_form_gis', function($rootScope, $http, $itfreer_form_core, $itfreerHttp) {
		$itfreer_form_gis = {

			// 加载第一条数据
			setGisConfig : function(formName, data){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.setEditRow(formName, data[0]);
			},

			// 设置地图的默认配置
			setDefulatConfig : function(successFunction){
				$itfreerHttp.setDefulatConfig(function(data){
					if(successFunction!=null){
						successFunction();
					}
					$.messager.alert('系统提示', '设置成功！');
				},function(xhr){
					$.messager.alert('系统提示', '设置失败！');
				})
			}
		};
		for(f in $itfreer_form_gis){
			$rootScope[f] = $itfreer_form_gis[f];
		}
		return $itfreer_form_gis;
	});

	/* 
	 * 加载服务器
	 */
	itfreerformgisModule.run(function($rootScope, $itfreer_form_gis) {
	  	
	});
}(window, angular));
/**itfreer.form.safe.js**/
/**
 * 定义itfreer.form.safe模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义运维模块
	 */
	var itfreerformsafeModule = angular.module('itfreer.form.safe', ['itfreer.form.core']);

	/**
	 * 定义表单变量
	 */
	itfreerformsafeModule.value('$domainObject',{
		// 选择的字典域
		selectedDomain : {},
		// 选择的字典域
		selectedDomainRow : {},
		// 字典表名称
		domainTableName : "",
		// 域名称控制
		isAddDomain : {},
		// 表单名称
		formObjectName : ""
	});

	/**
	 * 定义表单数据访问服务
	 */
	itfreerformsafeModule.factory('$itfreer_form_safe', 
		function($rootScope, $http, $domainObject, $itfreer_core, 
			$itfreerHttp, $formObject, $itfreer_form_core) {
		$itfreer_form_safe = {
			// 清除角色缓存
			clearRoleCache : function(){
				$itfreerHttp.clearRoleCache(
					function(data){
						$.messager.alert('系统提示', '应用成功。请相关用户重新登录系统！');
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '应用失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '应用失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '应用失败！原因：请求超时！');
						}
					}
				);
			},

			// 清除工作时间设置缓存
			clearWorkDayCache : function(){
				$itfreerHttp.clearWorkDayCache(
					function(data){
						$.messager.alert('系统提示', '应用成功！');
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
								$.messager.alert('系统提示', '应用失败！原因：'+xhr.responseText);
						}else{
							$.messager.alert('系统提示', '应用失败！原因：请求超时！');
						}
					}
				);
			},

			// 重新载入委托信息设置缓存
			reloadWt : function(){
				$itfreerHttp.reloadWt(
					function(data){
						$.messager.alert('系统提示', '委托成功！请重新登录系统');
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
								$.messager.alert('系统提示', '委托失败！原因：'+xhr.responseText);
						}else{
							$.messager.alert('系统提示', '委托失败！原因：请求超时！');
						}
					}
				);
			},

			// 停止使用角色委托
			enableRoleWts : function(){
				var delOk = confirm('确定取消选择的角色委托?');
				if(!delOk){
					return;
				}
				var rows = $formObject.user.editList.checkedRows;
				if(rows==null){
					return;
				}
				debugger;
				var keys = $formObject.user.keyField+":in";
				var values = "";
				var dRows = [];
				rows.forEach(function(e){  
					if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
						if (typeof (e[$formObject.user.keyField]) == 'string'){
							values += "'"+e[$formObject.user.keyField] + "',";
						}else{
							values += e[$formObject.user.keyField] + ",";
						}
						dRows.push(e);
					}
				});
				if(values!=""){
					values = values.substr(0, values.length-1);
					var rowMap = {};
					rowMap[keys] = values;
					$itfreerHttp.enableRoleWt(rowMap,
						function(data){
							$rootScope.$apply(function() {
								rows.forEach(function(e){  
									if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
										e["S_ISUSE"]="1";
									}
								});
							});
						}, 
						function(xhr){
							if(xhr.hasOwnProperty('responseText') 
									&& xhr.responseText!=null
									&& xhr.responseText!=''){
								if(xhr.responseText.length>300){
									alert('取消失败！原因：未授权！');
								}else{
									alert('取消失败！原因：'+xhr.responseText);
								}
							}else{
								alert('取消失败！原因：请求超时！');
							}
						}
					);
				}
			},

			// 修改密码
			savePassword : function() {
				$itfreerHttp.savePassword($formObject.password.oldPW, $formObject.password.newPW, $formObject.password.rnewPW,
					function(data){
						
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '修改密码失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '修改密码失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '修改密码失败！原因：请求超时！');
						}
					}
				);
			},

			// treeGirdName : 树Grid的名称
			initDomainPara : function(treeGirdName, keyField, idField, pIDField, orderField, treeJBField, treeIsChildField){
				var formName = "domainform";
				$formObject[formName] = {};
				$formObject[formName].treeGirdName = treeGirdName;
				$formObject[formName].keyField = keyField;
				$formObject[formName].orderField = orderField;
				$formObject[formName].idField = idField;
				$formObject[formName].pIDField = pIDField;
				// 树级别字段
				$formObject[formName].treeJBField = treeJBField;
				// 树是否叶子节点字段
				$formObject[formName].treeIsChildField = treeIsChildField;
			},
			
			// 添加新字典
			addNewDomain : function(){
				$domainObject.isAddDomain.value = true;
				var obj = {};
				var guid = $itfreer_core.getGUID();
				obj["DOMAINID"] = guid;
				obj[$formObject.isNew] = true;
				obj["_IS_DOMAIN_TRUE"] = true;
				// 默认表
				$domainObject.domainTableName = "DATA_DEFULATDOMAIN";
				$itfreer_form_core.setEditRow("domainform", obj);
			},
			
			// 添加顶级字典项
			addTopDomainItem : function(){
				$domainObject.isAddDomain.value = false;
				if($domainObject.selectedDomainRow.value==null
						|| !$domainObject.selectedDomainRow.value.hasOwnProperty("attributes")
						|| !$domainObject.selectedDomainRow.value.attributes){
					$.messager.alert('系统提示', '当前字典不可编辑！');
					return;
				}
				
				var obj = {};
				var guid = $itfreer_core.getGUID();
				obj["DOMAINID"] = guid;
				obj[$formObject.isNew] = true;
				obj["_IS_DOMAIN_TRUE"] = true;
				
				var domainName = $domainObject.selectedDomain.value;
				var msgs = domainName.split(":");
				obj["DOMAINNAME"] = msgs[1];
				$domainObject.domainTableName = msgs[0];
				
				$itfreer_form_core.setEditRow("domainform", obj);
			},
			
			// 添加下级字典项
			addNextDomainItem : function(){
				$domainObject.isAddDomain.value = false;
				if($domainObject.selectedDomainRow.value==null
						|| !$domainObject.selectedDomainRow.value.hasOwnProperty("attributes")
						|| !$domainObject.selectedDomainRow.value.attributes){
					$.messager.alert('系统提示', '当前字典不可编辑！');
					return;
				}
				
				var treeGridControl = $('#'+$formObject["domainform"].treeGirdName);
				var selectedNode = treeGridControl.treegrid('getSelected');
				if(selectedNode==null){
					$.messager.alert('系统提示', '请选择一个父节点！');
					return;
				}
				
				var row = jQuery.extend(true, {}, $formObject["domainform"].defaultObject);
				row[$formObject.isNew]=true;
				row[$formObject["domainform"].pIDField] = selectedNode[$formObject["domainform"].idField];
				var guid = $itfreer_core.getGUID();
				row["DOMAINID"] = guid;
				row["_IS_DOMAIN_TRUE"] = true;
				
				row["ISUSER"] = '1';
				row["ISEDIT"] = '1';
				row['DOMAINCODE'] = $formObject['domainform'] && $formObject['domainform'].curOldRow && $formObject['domainform'].curOldRow.DOMAINCODE;
				
				var domainName = $domainObject.selectedDomain.value;
				var msgs = domainName.split(":");
				row["DOMAINNAME"] = msgs[1];
				$domainObject.domainTableName = msgs[0];
				
				$itfreer_form_core.setEditRow("domainform", row);
			},
			
			// 编辑字典项
			editDomainItem : function(){
				$domainObject.isAddDomain.value = false;
				if($domainObject.selectedDomainRow.value==null
						|| !$domainObject.selectedDomainRow.value.hasOwnProperty("attributes")
						|| !$domainObject.selectedDomainRow.value.attributes){
					$.messager.alert('系统提示', '当前字典不可编辑！');
					return;
				}
				
				var treeGridControl = $('#'+$formObject["domainform"].treeGirdName);
				var row = treeGridControl.treegrid('getSelected');
				if(row==null){
					$.messager.alert('系统提示', '请选择一个父节点！');
					return;
				}
				
				row["_IS_DOMAIN_TRUE"] = true;
				var domainName = $domainObject.selectedDomain.value;
				var msgs = domainName.split(":");
				row["DOMAINNAME"] = msgs[1];
				$domainObject.domainTableName = msgs[0];
				$itfreer_form_core.setEditRow("domainform", row);
			},
			
			delDomainItem : function(){
				if($domainObject.selectedDomainRow.value==null
						|| !$domainObject.selectedDomainRow.value.hasOwnProperty("attributes")
						|| !$domainObject.selectedDomainRow.value.attributes){
					$.messager.alert('系统提示', '当前字典不可编辑！');
					return;
				}
				
				var treeGridControl = $('#'+$formObject["domainform"].treeGirdName);
				var row = treeGridControl.treegrid('getSelected');
				if(row==null){
					$.messager.alert('系统提示', '请选择一个父节点！');
					return;
				}
				
				$.messager.confirm("操作确认", '确定删除此记录?', function(r){
					if(r){
						row["_IS_DOMAIN_TRUE"] = true;
						var domainName = $domainObject.selectedDomain.value;
						var msgs = domainName.split(":");
						row["DOMAINNAME"] = msgs[1];
						$domainObject.domainTableName = msgs[0];
						$itfreer_form_core.delTreeSelectedRows("domainform", $domainObject.domainTableName, row);
					}
				});
			},
			
			// 保存字典域
			saveDomain : function(successFunction, failFunction){
				$itfreer_form_core.save("domainform", $domainObject.domainTableName,null, null, null, null, successFunction, failFunction);
			},
			
			// 初始化字典数据
			initDomainData : function(){
				var domainName = $domainObject.selectedDomain.value;
				if(!domainName){
					return;
				}

				var msgs = domainName.split(":");
				$itfreerHttp.getDomainsEx(msgs[0], msgs[1], true, function(treedata){
					if(treedata==null){
						treedata=[];
					}
					var treeGridControl = $('#'+$formObject["domainform"].treeGirdName);
					treeGridControl.treegrid('loadData', treedata);
				},
				function(xhr){
					if(xhr.hasOwnProperty('responseText') 
							&& xhr.responseText!=null
							&& xhr.responseText!=''){
						if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
							$.messager.alert('系统提示', '字典获取失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
						}else{
							$.messager.alert('系统提示', '字典获取失败！原因：'+xhr.responseText);
						}
					}else{
						$.messager.alert('系统提示', '字典获取失败！原因：请求超时！');
					}
				});
			},

			/**
			 * 人员选择组件，并增加去除重复
			 */
			assignmentUserChild : function(editRow, childTableName, selectedRows) {
				if(selectedRows){
					if(!editRow.childValues){
						editRow.childValues = {};
					}
					var currentRows = editRow.childValues[childTableName];
					selectedRows.forEach(function(e){
						var row = jQuery.extend(true, {}, e);
						row[$formObject.isNew] = true;
						row["GUID"]="";
						var isNotExist=true;
						currentRows.forEach(function(e){
							var curtRow = jQuery.extend(true, {}, e);
							if(curtRow['S_USERID']==row['S_USERID']){
								isNotExist=false;
							}
						});
						if(isNotExist){
						 	editRow.childValues[childTableName].push(row);
						}
					});
				}
			}
		};
		for(f in $itfreer_form_safe){
			$rootScope[f] = $itfreer_form_safe[f];
		}
		$rootScope.domainObject = $domainObject;
		return $itfreer_form_safe;
	}); 

	/**
	 * 委托状态
	 */
	itfreerformsafeModule.filter("asRoleWtState", function () {
	    return function (input) {
	    	if(input==1){
	    		return "已结束";
	    	}else{
	    		return "委托中";
	    	}
	    };
	});
	
	/* 
	 * 加载服务器
	 */
	itfreerformsafeModule.run(function($rootScope, $itfreer_form_safe, $domainObject) {
	  	
	});
}(window, angular));
/**itfreer.js**/
/**
 * 定义总模块
 */
(function(window, angular, undefined){

	/**
	* 定义总模块
	*/
	var itfreer = angular.module('itfreer', 
		['itfreer.form.builder', 'itfreer.form.gis', 'itfreer.form.safe','itfreer.arcgis.map']);

	/**
	 * 定义特定交互下的特定方法
	 */
	itfreer.factory('$itfreer', function($rootScope, $http) {
		$itfreer = {

			// 临时打开的窗口
			windowName : '',

			// 打开窗口
			openWindow : function(windowName,option){
				windowName = windowName ? windowName : 'edit';
				if(option){
					$('#'+windowName).window(option);
				}
				$('#'+windowName).window('open');
				$itfreer.windowName = windowName;
			},
			
			// 关闭窗口
			closeWindow : function(windowName){
				windowName = windowName ? windowName : $itfreer.windowName;
				console.log('closeWindow:'+windowName);
				$('#'+windowName).window('close');
			}
		};
		for(f in $itfreer){
			$rootScope[f] = $itfreer[f];
		}
		return $itfreer;
	});

	/* 
	 * 加载服务器
	 */
	itfreer.run(function($rootScope, $itfreer) {
	  	
	});
}(window, angular));